<?php

namespace app\api\logic;

use app\api\cache\CommunitySignCache;
use app\api\cache\KeysUtil;
use app\api\cache\Marketing;
use app\api\cache\MemberAccountCache;
use app\api\cache\RedisCache;
use app\api\consDir\CommunityConst;
use app\api\consDir\ErrorConst;
use app\api\consDir\SandConst;
use app\api\services\AlipayService;
use app\api\services\CommunityService;
use app\api\services\CouponService;
use app\api\services\MemberInfoService;
use app\api\services\MemberService;
use app\api\services\PayService;
use app\api\services\RabbitMqService;
use app\api\services\SandService;
use app\common\libs\Singleton;
use app\common\models\Community\Community;
use app\common\models\Community\CommunityChangeLog;
use app\common\models\Community\CommunityExchangeLog;
use app\common\models\Community\CommunityLockLog;
use app\common\models\Community\CommunityOpOrder;
use app\common\models\Community\CommunityOrder;
use app\common\models\Community\CommunityRank;
use app\common\models\Community\CommunitySignUser;
use app\common\models\Community\CommunityTaskLog;
use app\common\models\Community\CommunityTasksLog;
use app\common\models\Community\CommunityUser;
use app\common\models\Community\CommunityUserTransferLog;
use app\common\models\Community\CommunityWithdraw;
use app\common\models\Community\PrepayCommunityOrder;
use app\common\models\Community\Rank;
use app\common\models\Community\RankMember;
use app\common\models\Member\Account;
use app\common\models\Member\Finance;
use app\common\models\Member\Member;
use app\common\models\Member\MemberCommunityAmountLog;
use app\common\models\Member\MemberGxzLog;
use app\common\models\Member\MemberNum;
use app\common\models\Member\MemberWithdraw;
use app\common\models\Order\OrderError;
use app\common\models\Order\OrderPay;
use app\common\models\Order\OrderShop;
use app\common\models\Shop\Shop;
use app\common\models\Sys\ShopConfig;
use app\common\utils\CommonUtil;
use app\common\utils\RedLock;
use DateTime;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\facade\Db;
use think\facade\Log;

/**
 * 社区模块
 * Class MemberLogic
 * @package app\api\logic
 */
class CommunityLogic extends BaseLogic
{
    use Singleton;

    /**
     * @param $page
     * @param $pageSize
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function communityHistoryList($page, $pageSize): array
    {

        $list = CommunityUser::getInstance()
            ->field('id,community_name,address,community_status,user_id,last_enter_amount,shop_amount,shop_num,last_enter_time')
            ->where('user_ids', 'like', '%;' . $this->userinfo->id . ';%')
            ->limit(($page - 1) * $pageSize, $pageSize)
            ->select();
        if (empty($list)) {
            return [];
        } else {
            $list = $list->toArray();
        }
        $userIds = array_column($list, 'userId');
        $userInfos = MemberService::getInstance()->getUserInfoIds($userIds);

        foreach ($list as &$val) {
            $val['userInfo'] = $userInfos[$val['userId']] ?? [];
            $val['communityAmount'] = 0;
            $val['orderAmount'] = 0;
            $val['nextEnterTime'] = date('Y-m-d H:i:s', strtotime('+7 day', strtotime($val['lastEnterTime'])));
        }

        return ['rows' => $list];
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function inPayOrder(): array
    {
        $where = [
            ['user_id', '=', $this->userinfo->id],
//            ['status', '=', 1],
            //            ['expire_at', '>', date('Y-m-d H:i:s')],
        ];
        $field = 'status,order_no,id,expire_at,community_id,price,sign_price,prepay_price';
        $list = CommunityOrder::getInstance()->where($where)->field($field)->order('id desc')->find();
        if (empty($list)) {
            return [];
        }
        $list = $list->toArray();
        if ($list['status'] != 1) {
            return [];
        }
        if ($list['expireAt'] <= date('Y-m-d H:i:s')) {
            return [];
        }
        $where = [
            ['user_id', '=', $this->userinfo->id],
            ['sign_status', '=', 1],
            ['expire_at', '>', date('Y-m-d')],
        ];
        $list['signPrice'] = CommunitySignUser::getInstance()->where($where)->order('id desc')->value('community_amount');
        $list['exTime'] = strtotime($list['expireAt']) - time();
        $list['communityInfo'] = CommunityService::getInstance()->getCommunityUser($list['communityId']);

        return $list;
    }

    /**
     * @param $type
     * @param $page
     * @param $pageSize
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function communityUserLog($status, $type, $page, $pageSize): array
    {
        $arr = [
            0 => '全部',
            1 => '提现',
            2 => '社区收益',
            3 => '社区入驻',
            4 => '社区签到',
//            5 => '手续费',
            6 => '商家收益',
//            7 => '商城收益',
            8 => '事业部收益',
//            9 => '签到收益',
            //            10 => '升级服务商',
            11 => '区域收益',
            12 => '区域会员收益',
            13 => '服务商收益',

        ];
        $list = CommunityService::getInstance()->communityUserLog($status, $type, $this->userinfo->id, $page, $pageSize);
        //$userBalance = MemberService::getInstance()->finance($this->userinfo->id);
        //$amountPrice = $userBalance['communityAmount'];
        return ['rows' => $list, 'typeList' => $arr];
    }

    /**
     * @param $type
     * @param $timeType
     * @param $page
     * @param $pageSize
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function rank($type, $timeType, $page, $pageSize): array
    {
        switch ($type) {
            case 1: //社区
                $list = CommunityService::getInstance()->getCommunityRank($timeType, $page, $pageSize);
                break;
            default:
                //$list = CommunityService::getInstance()->getCommunityUserRank($timeType, $page, $pageSize, $this->userinfo->id);
                $list = [];
        }
        return $list;
    }

    /**
     * 新排名
     * @param $timeType
     * @param $page
     * @param $pageSize
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function communityRank($timeType, $page, $pageSize): array
    {
        $thisWeekStart = date('Y-m-d H:i:s', strtotime('this week Monday'));
        $lastWeekStart = date('Y-m-d H:i:s', strtotime('last week Monday'));
        if(!in_array($timeType,[1,2])){
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }
        $arr = [1 => $thisWeekStart, 2 => $lastWeekStart];
        $where = [
            ['is_switch','=',1],
            ['condition_type','=',1],
            ['status','=',1],
        ];
        $min = Rank::getInstance()->where($where)->value('condition_value') ?: 0;
        $where = [
            ['c.start_time','=',$arr[$timeType]],
            ['c.num','>=',$min]
        ];
        $userIds = RankMember::getInstance()->where('deleted',0)->column('user_id');
        if(!empty($userIds)){
            $where[] = ['m.id','not in',$userIds];
        }
        $infoSql = CommunityRank::getInstance()
            ->alias('c')
            ->leftJoin('member m','c.user_id=m.id')
            ->field('c.user_id,m.phone,m.user_name,m.avatar,c.num')
            ->where($where)
            ->order('c.num desc')
            ->buildSql();
        Db::execute('SET @rank= 0;');
        $rankSql = Db::table($infoSql . ' g')
            ->field('(@rank:=@rank + 1) AS rank,g.*')
            ->buildSql();
        //列表数据
        $list = Db::table($rankSql . ' r')->page($page, $pageSize)->select();

        $where = [
            ['c.start_time','=',$arr[$timeType]],
        ];
        if(!empty($userIds)){
            $where[] = ['m.id','not in',$userIds];
        }
        $infoSql = CommunityRank::getInstance()
            ->alias('c')
            ->leftJoin('member m','c.user_id=m.id')
            ->field('c.user_id,m.phone,m.user_name,m.avatar,c.num')
            ->where($where)
            ->order('c.num desc')
            ->buildSql();
        Db::execute('SET @rank= 0;');
        $rankSql = Db::table($infoSql . ' g')
            ->field('(@rank:=@rank + 1) AS rank,g.*')
            ->buildSql();
        //我的排名
        Db::execute('SET @rank= 0;');
        $self = Db::table($rankSql . ' r')->where('r.user_id', $this->userinfo->id)->find();
        if(empty($self)) {
            $self = Db::table('member')->where('id',$this->userinfo->id)->field('id user_id,phone,user_name,avatar')->find();
            $self['num'] = 0;
            $self['rank'] = 0;
        }else{
            $self['rank'] =  $self['num'] >= $min ? $self['rank'] : 0;
        }

        return ['rows' => $list, 'self' => $self];
    }

    /**
     * @param $orderNo
     * @param $isBalance
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function paySign($orderNo, $isBalance): array
    {
        if (!RedLock::getInstance()->lock('paySign_' . $this->userinfo->id, 1)) {
            CommonUtil::throwException(ErrorConst::FREQUENT_ERROR, ErrorConst::FREQUENT_ERROR_MSG);
        }
        $cache = CommunitySignCache::getSign($this->userinfo->id);
        if (!$cache) {
            CommonUtil::throwException(ErrorConst::ORDER_TIME_OUT_ERROR, ErrorConst::ORDER_TIME_OUT_ERROR_MSG);
        }

        $userSign = CommunityService::getInstance()->getSign($orderNo);
        if (empty($userSign)) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }

        $payInfo = CommunityService::getInstance()->payOrderSign($userSign);
        if (!$payInfo) {
            CommonUtil::throwException(ErrorConst::SYSTEM_ERROR, ErrorConst::SYSTEM_ERROR_MSG);
        }
        if ($isBalance) {
            $userBalance = MemberService::getInstance()->finance($this->userinfo->id);
            $amountPrice = $userBalance['communityAmount'];
            if ($amountPrice < $userSign['payPrice']) {
                CommonUtil::throwException(ErrorConst::NO_PRICE_ERROR, ErrorConst::NO_PRICE_ERROR_MSG);
            }

            $return = CommunityService::getInstance()->paySignByBalance($this->userinfo->id, $userSign);
            if (!$return) {
                CommonUtil::throwException(ErrorConst::SYSTEM_ERROR, ErrorConst::SYSTEM_ERROR_MSG);
            }
            return ['isBalance' => 1, 'expireAt' => $payInfo['expire_at'], 'price' => $payInfo['pay_price']];
        } else {
            $userInfo = MemberService::getInstance()->getUserInfo($this->userinfo->id);
            $pay = PayService::getInstance()->toPay($payInfo, $userInfo);
            return ['isBalance' => 0, 'payInfo' => $pay, 'expireAt' => $payInfo['expire_at'], 'price' => $payInfo['pay_price']];
        }
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function sign(): array
    {
        if (!RedLock::getInstance()->lock('sign:' . $this->userinfo->id, 3)) {
            CommonUtil::throwException(ErrorConst::FREQUENT_ERROR, ErrorConst::FREQUENT_ERROR_MSG);
        }

        $settleTime = CommunityService::getInstance()->getCommunityConfig('check_in_settlement_time');
        if (!$settleTime) {
            CommonUtil::throwException(ErrorConst::SIGN_IN_NOT_ERROR, ErrorConst::SIGN_IN_NOT_MSG);
        }
        $userSigned = RedisCache::get(KeysUtil::getCommunitySignUserKey($this->userinfo->id));
        if($userSigned){
            CommonUtil::throwException(ErrorConst::HAVE_SIGN_ERROR, ErrorConst::HAVE_SIGN_ERROR_MSG);
        }
        $sign = CommunityService::getInstance()->getUserBag($this->userinfo->id, 1);
        if (!empty($sign)) {
            CommonUtil::throwException(ErrorConst::HAVE_SIGN_ERROR, ErrorConst::HAVE_SIGN_ERROR_MSG);
        }

        $data['signTime'] = CommunityService::getInstance()->getSignTimes();

        $allSignCount = CommunityService::getInstance()->getCommunityConfig('check_in_max_num');
        $end = strtotime(date('Y-m-d 23:59:59')) - time();
        $key = KeysUtil::getCommunitySignIncrKey($data['signTime']['start']);
        $incrCount = RedisCache::incr($key);
        RedisCache::expire($key, $end);
        if($incrCount > $allSignCount){
            CommonUtil::throwException(ErrorConst::NO_SIGN_ERROR, ErrorConst::NO_SIGN_ERROR_MSG);
        }
        Log::error('incrCount:'.$incrCount);
        /*$allSignCount = CommunityService::getInstance()->getCommunityConfig('check_in_max_num');
        if ($thisSignCount >= $allSignCount) {
            CommonUtil::throwException(ErrorConst::NO_SIGN_ERROR, ErrorConst::NO_SIGN_ERROR_MSG);
        }*/

        $payPrice = CommunityService::getInstance()->getCommunityConfig('check_in_fee');
        if ($payPrice == 0) {
            $communityAmount = CommunityService::getInstance()->getCommunityConfig('check_in_success_award');
            $expireDate = CommunityService::getInstance()->getCommunityConfig('check_in_valid_time');
            $expireAt = date('Y-m-d H:i:s', strtotime('+' . $expireDate . ' day') - 3600);
            $event["exchange"] = config('rabbitmq.info_queue');
            RabbitMqService::send($event, ['type' => 'community_sign', 'data' => ['id' => $this->userinfo->id]]);
            return ['isPay' => 0, 'payPrice' => 0, 'communityAmount' => $communityAmount, 'expire_at' => $expireAt, 'orderNo' => ''];
        } else {
            $userBalance = MemberService::getInstance()->finance($this->userinfo->id);
            $amountPrice = $userBalance['communityAmount'];
            //生成订单
            $data = CommunityService::getInstance()->addCommunitySignOrder($this->userinfo->id, $payPrice);
            return ['isPay' => 1, 'payPrice' => $payPrice, 'communityAmount' => $amountPrice, 'orderNo' => $data['order_no'] ?? ''];
        }

    }

    /**
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function signInfo(): array
    {
        $data['rule'] = SysLogic::getInstance()->article(7);
        $data['signTime'] = CommunityService::getInstance()->getSignTimes();
        $data['settleTime'] = CommunityService::getInstance()->getCommunityConfig('check_in_settlement_time');
        $data['allSignCount'] = 0;
        $data['thisSignCount'] = 0;
        $data['is_signed'] = 0;
        if (!$data['signTime']['inPay']) {
            return $data;
        }
        //过期
        $where = [
            ['expire_at', '<', date('Y-m-d H:i:s')],
            ['user_id', '=', $this->userinfo->id],
            ['sign_status', '=', 1],
        ];
        CommunitySignUser::getInstance()->where($where)->update(['sign_status' => 3, 'refund_at' => date('Y-m-d H:i:s')]);

        $data['allSignCount'] = CommunityService::getInstance()->getCommunityConfig('check_in_max_num');
        //是否已签到
        $where = [
            ['create_at', '>', date('Y-m-d')],
            ['user_id', '=', $this->userinfo->id],
            ['type', '=', 1]
        ];
        $data['is_signed'] = CommunitySignUser::getInstance()->where($where)->count() ? 1 : 0;

        $where = [
            ['order_status', '=', 2],
            ['type', '=', 1],
            ['create_at', '>=', date('Y-m-d') . ' ' . $data['signTime']['start']],
        ];
        $data['thisSignCount'] = CommunitySignUser::getInstance()->where($where)->count('id');
        $data['thisSignCount'] = min($data['thisSignCount'], $data['allSignCount']);
        $sign = CommunityService::getInstance()->getUserBag($this->userinfo->id, 1);
        if (!empty($sign)) {
            $data['signTime']['inPay'] = false;
            return $data;
        }
        return $data;
    }

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function myCommunityList($page, $pageSize, $status): array
    {
        //4待经营  6考核中 7被领取 8：永久社区
        if (!in_array($status, [1, 4, 6, 8])) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }
        $where = [
            ['user_id', '=', $this->userinfo->id],
            ['community_status', '=', $status],
        ];
        //考核中
        if ($status == 6) {
            $where[] = ['is_sign', '=', 0];
        }
        //已释放
        $whereOr = [];
        if ($status == 1) {
            $whereOr[] = ['is_sign', '=', 1];
            $whereOr[] = ['user_id', '=', $this->userinfo->id];
        }
        $field = 'community_name,user_amount,community_id,address,community_status,last_enter_amount,op_price,
        shop_amount,shop_num,last_enter_time,user_count,update_at,op_time,last_order_id,is_pay_service,op_order_no,
        is_first,last_op_order_no,total_amount,is_sign,user_id,is_op_transfer,permanent_time';
        $list = CommunityUser::getInstance()
            ->where($where)
            ->whereOr(function ($query) use ($whereOr) {
                $query->where($whereOr);
            })
            ->field($field)
            ->order(['last_enter_time' => 'desc', 'op_time' => 'desc'])
            ->limit(($page - 1) * $pageSize, $pageSize)
            ->select();

        if (empty($list)) {
            return [];
        }

        $list = $list->toArray();
        $checkingDays = CommunityService::getInstance()->getCommunityConfig('checking_days');
        $transferStatus = Member::getInstance()->where('id', $this->userinfo->id)->value('transfer_status');
        $buyCommunityConfig = CommunityService::getInstance()->getCommunityConfig('buy_community_config');
        $isExchange = Member::getInstance()->where('id', $this->userinfo->id)->value('is_exchange');
        $isUserTransfer = CommunityService::getInstance()->getCommunityConfig('is_user_transfer');
        foreach ($list as &$val) {
            $val['expireAt'] = $val['opTime'] ? strtotime('+' . $checkingDays . ' days', strtotime($val['opTime'])) : '';
            $val['updateAt'] = $val['updateAt'] ? strtotime($val['updateAt']) : '';
            $val['opTime'] = $val['opTime'] ? strtotime($val['opTime']) : '';
            //考核到期后，显示转让
            $val['isTransfer'] = $val['isSign'] == 0 && time() > $val['expireAt'] ? 1 : 0;
            if ($transferStatus == 1) {
                $val['isTransfer'] = 0;
            }
            //一键关闭转让
            if ($isUserTransfer == 0){
                $val['isTransfer'] = 0;
            }
            //考核中 立即经营(锁定社区)
            $val['isLock'] = 0;
            if ($status == 6) {
                if ($buyCommunityConfig['lock_status'] == 1 && $val['totalAmount'] > $buyCommunityConfig['lock_price']) {
                    $val['isLock'] = 1;
                }
            }

            //开启经营中转让社区
            $val['isConvert'] = 0;
            //开启经营中社区兑换
            $val['isExchange'] = 0;
            if ($status == 8) {
                if ($buyCommunityConfig['transfer_status'] == 1 && $val['isOpTransfer'] == 0) {
                    $val['isConvert'] = 1;
                }
                //社区已经转让至转让大厅，兑换社区不能展示
                $where = [
                    'ex_community_id' => $val['communityId'],
                    'user_id' => $this->userinfo->id,
                ];
                $num = CommunityExchangeLog::getInstance()->where($where)->order('id desc')->value('num') ?: 0;
                if ($buyCommunityConfig['exchange_status'] == 1 && $val['isOpTransfer'] == 0 && $num < $buyCommunityConfig['exchange_count']) {
                    if($isExchange == 1){
                        $val['isExchange'] = 1;
                    }
                }
            }
            //经营中天数
            $val['opDays'] = 0;
            if ($val['permanentTime']) {
                $time = strtotime($val['permanentTime']);
                $remain = time() - $time;
                $val['opDays'] = floor($remain / 86400);
            }
            $val['lastEnterTime'] = $val['lastEnterTime'] ?: '暂时未入驻';
        }

        return ['rows' => $list];
    }

    /**
     * @param $orderNo
     * @param $isBag
     * @param $type
     * @param $payPassword
     * @param $paySubType
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function payOrder($orderNo, $isBag, $type, $payPassword, $paySubType): array
    {
        if (!RedLock::getInstance()->lock('payOrder:' . $orderNo, 1)) {
            CommonUtil::throwException(ErrorConst::FREQUENT_ERROR, ErrorConst::FREQUENT_ERROR_MSG);
        }

        if (!in_array($type, [1, 2, 3, 4])) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }
        //1微信 2支付宝 3余额 4杉德支付
        $payChanel = RedisCache::hGetAll(KeysUtil::getSystemConfigKey('pay'));
        $payChanel = $payChanel ? json_decode($payChanel['community'],1) : [];
        if(empty($payChanel)){
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, '支付通道错误');
        }
        $payArr = [1 => $payChanel['wechatpay'],2 => $payChanel['alipay'],3 => $payChanel['balance'],4 => $payChanel['purse']];
        if(!isset($payArr[$type]) || $payArr[$type] == 0){
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, '支付方式错误');
        }

        //获取订单
        //$orderInfo = CommunityService::getInstance()->getOrder($orderNo);
        $orderInfo = RedisCache::get(KeysUtil::getCommunityOrderKey($orderNo));
        $orderInfo = $orderInfo ? json_decode($orderInfo, true) : [];

        //订单不存在 订单状态错误      订单用户id错误 ，订单时间超时
        if (empty($orderInfo) || $orderInfo['status'] != 1 || $orderInfo['user_id'] != $this->userinfo->id || $orderInfo['expire_at'] < date('Y-m-d H:i:s')) {
            CommonUtil::throwException(ErrorConst::NO_ORDER_ERROR, ErrorConst::NO_ORDER_ERROR_MSG);
        }

        if ($type == 3) {
            $account = MemberService::getInstance()->account($this->userinfo->id);
            if (empty($account)) {
                CommonUtil::throwException(ErrorConst::NO_PAY_PASSWORD_ERROR, ErrorConst::NO_PAY_PASSWORD_ERROR_MSG);
            }

            //验证支付密码
            if ($account['payPwd'] != $payPassword) {
                CommonUtil::throwException(ErrorConst::PAY_PASSWORD_ERROR, ErrorConst::PAY_PASSWORD_ERROR_MSG);
            }
        }

        $amountPrice = 0;
        $signPrice = 0;
        //获取余额
        if ($type == 3) {
            $userBalance = MemberService::getInstance()->finance($this->userinfo->id);
            $amountPrice = $userBalance['amount'];
        }
        //获取红包
        if ($isBag) {
            $userBag = CommunityService::getInstance()->getUserBag($this->userinfo->id);
            $signPrice = $userBag['communityAmount'] ?? 0;
        }

        $price = $orderInfo['price'];
        $payPrice = bcsub($price, $signPrice, 2);
        //扣除预付金额
        $payPrice = bcsub($payPrice, $orderInfo['prepay_price'], 2);
        $isBalance = 0;
        if ($type == 3 && $amountPrice < $payPrice) {
            CommonUtil::throwException(ErrorConst::NO_PRICE_ERROR, ErrorConst::NO_PRICE_ERROR_MSG);
        }
        if ($type == 3) {
            //社区余额
            $amountPrice = $payPrice;
            $thirdPayPrice = 0;
            $isBalance = 1;
        } else {
            $thirdPayPrice = $payPrice;
        }

        $payInfo = CommunityService::getInstance()->payOrder($orderInfo, $thirdPayPrice, $amountPrice, $signPrice, $type);
        if (!$payInfo) {
            CommonUtil::throwException(ErrorConst::SYSTEM_ERROR, ErrorConst::SYSTEM_ERROR_MSG);
        }
        //有微信支付
        //$userInfo = MemberService::getInstance()->getUserInfo($this->userinfo->id);
        $userInfo = RedisCache::hGetAll(KeysUtil::getMemberInfoKey($this->userinfo->id));
        $pay = [];
        if ($isBalance) {
            //余额全付
            $info = [
                'pay_status' => 3,
                'pay_no' => $payInfo['pay_no'],
                'money' => $payInfo['community_pay_amount'],
                'trade_no' => '',
                'receipt_data' => '',
            ];

            //$info = PayService::getInstance()->payFormOrder($info);
            $event["exchange"] = config('rabbitmq.order_callback_queue');
            RabbitMqService::send($event, $info);
            if (!$info) {
                CommonUtil::throwException(ErrorConst::SYSTEM_ERROR, ErrorConst::SYSTEM_ERROR_MSG);
            }
        } elseif ($type == 4) {
            //杉德支付
            $ret = SandLogic::getInstance()->accountBalanceQuery($userInfo['id']);
            if (empty($ret)) {
                CommonUtil::throwException(ErrorConst::PARAM_ERROR, '个人钱包未开户');
            }
            if (env('test.is_test') == 1) {
                if ($ret['accountList'][0]['availableBal'] < 0.01) {
                    CommonUtil::throwException(ErrorConst::NO_PRICE_ERROR, ErrorConst::NO_PRICE_ERROR_MSG);
                }
            } else {
                if ($ret['accountList'][0]['availableBal'] < $thirdPayPrice) {
                    CommonUtil::throwException(ErrorConst::NO_PRICE_ERROR, ErrorConst::NO_PRICE_ERROR_MSG);
                }
            }
            Log::info($orderInfo['order_no'] . 'payOrder：支付金额：' . $thirdPayPrice);
            if (env('test.is_test') == 1) {
                $thirdPayPrice = 0.01;
            }
            $payeeUserId = RedisCache::hGet(KeysUtil::getCommunityInfo($orderInfo['community_id']), 'user_id');
            if (empty($payeeUserId)) { //平台
                $pay = SandLogic::getInstance()->orderCreate($this->userinfo->id, $thirdPayPrice, $payInfo['pay_no']);
            } else {
                /*
                //社区溢价收益
                $serviceEarnings = CommunityService::getInstance()->getCommunityConfig('member_settlement_rate');
                $price = bcmul(bcmul($orderInfo['premium'], $serviceEarnings, 2), 0.01, 2);
                //扣除8%手续费
                $feeRate = CommunityService::getInstance()->getCommunityConfig('withdraw_fee');
                $fee = bcmul($price, bcmul($feeRate, 0.01, 2), 2);
                if ($signPrice > 0) {
                    $fee = bcsub($fee, $signPrice, 2);
                }
                Log::error('fee:' . $fee);
                //不够支付上一个人，先收回平台，平台再发放给用户
                if ($fee < 0) {
                    CommunityOrder::getInstance()->where('order_no', $orderNo)->update(['is_enough' => 1]);
                    $pay = SandLogic::getInstance()->orderCreate($this->userinfo->id, $thirdPayPrice, $payInfo['pay_no']);
                } else {
                    $fee = env('test.is_test') == 1 ? 0 : $fee;
                    $pay = SandLogic::getInstance()->transfer($thirdPayPrice, SandConst::PREFIX . $userInfo['id'], SandConst::PREFIX . $payeeUserId, $fee, $payInfo['pay_no'], 'confirm');
                }
                */

                //社区溢价收益
                //$serviceEarnings = CommunityService::getInstance()->getCommunityConfig('member_settlement_rate');
                $serviceEarnings = 100 - CommunityService::getInstance()->getCommunityConfig('transfer_rate');
                $price = bcmul(bcmul($orderInfo['premium'], $serviceEarnings, 2), 0.01, 2);
                $reduce = bcsub($price, $signPrice, 2);
                if ($orderInfo['type'] == 4 && $orderInfo['prepay_price'] > 0) {
                    //预付
                    $reduce = bcsub($reduce, $orderInfo['prepay_price'], 2);
                    if ($reduce < 0) {
                        CommunityOrder::getInstance()->where('order_no', $orderNo)->update(['is_enough' => 1]);
                        $pay = SandLogic::getInstance()->orderCreate($this->userinfo->id, $thirdPayPrice, $payInfo['pay_no']);
                    } else {
                        Log::info($orderInfo['order_no'] . '扣除金额：' . $reduce);
                        if (env('test.is_test') == 1) {
                            $reduce = 0;
                        }
                        $pay = SandLogic::getInstance()->transfer($thirdPayPrice, SandConst::PREFIX . $userInfo['id'], SandConst::PREFIX . $payeeUserId, $reduce, $payInfo['pay_no'], 'confirm');
                    }
                } else {
                    Log::info($orderInfo['order_no'] . '扣除金额：' . $reduce);
                    if (env('test.is_test') == 1) {
                        $reduce = 0;
                    }
                    $pay = SandLogic::getInstance()->transfer($thirdPayPrice, SandConst::PREFIX . $userInfo['id'], SandConst::PREFIX . $payeeUserId, $reduce, $payInfo['pay_no'], 'confirm');
                }
            }
        } else {
            $pay = PayService::getInstance()->toPay($payInfo, $userInfo, $type, $paySubType);
        }

        return ['payInfo' => $pay, 'isBalance' => $isBalance];
    }

    /**
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws DataNotFoundException
     */
    public function createPrepayOrder(): array
    {
        if (!RedLock::getInstance()->lock('createPrepayOrder:' . $this->userinfo->id, 1)) {
            CommonUtil::throwException(ErrorConst::FREQUENT_ERROR, ErrorConst::FREQUENT_ERROR_MSG);
        }
        $prepayTime = CommunityService::getInstance()->getCommunityConfig('prepay_time');
        if (empty($prepayTime)) {
            CommonUtil::throwException(ErrorConst::FREQUENT_ERROR, '预约时间不能为空');
        }

        list($start, $end) = explode('-', $prepayTime);
        $now = date('H:i');
        if ($now < $start || $now > $end) {
            CommonUtil::throwException(ErrorConst::FREQUENT_ERROR, '未到预约时间');
        }

        //今天抢购次数
        $prepayNum = CommunityService::getInstance()->getCommunityConfig('prepay_num');
        if (empty($prepayNum) || $prepayNum <= 0) {
            CommonUtil::throwException(ErrorConst::FREQUENT_ERROR, '暂无预约次数');
        }
        $where = [
            ['status', 'in', [1, 2]],
            ['create_at', '>=', date('Y-m-d')]
        ];
        $count = PrepayCommunityOrder::getInstance()->where($where)->count();
        if ($count >= $prepayNum) {
            CommonUtil::throwException(ErrorConst::FREQUENT_ERROR, '今天暂无预约次数');
        }
        $where = [
            ['user_id', '=', $this->userinfo->id],
            ['status', 'in', [1, 2]],
            ['create_at', '>=', date('Y-m-d')]
        ];
        $userCount = PrepayCommunityOrder::getInstance()->where($where)->count();
        $prepayEveryCount = CommunityService::getInstance()->getCommunityConfig('prepay_every_count');
        if ($userCount >= $prepayEveryCount) {
            CommonUtil::throwException(ErrorConst::FREQUENT_ERROR, '今天已预约社区');
        }

        //入门门槛
        $prepayJoinNum = CommunityService::getInstance()->getCommunityConfig('prepay_join_num');
        if ($prepayJoinNum > 0) {
            $where = [
                ['user_id', '=', $this->userinfo->id],
                ['status', '=', 2]
            ];
            $count = CommunityOrder::getInstance()->where($where)->count();
            if ($count > $prepayJoinNum) {
                CommonUtil::throwException(ErrorConst::FREQUENT_ERROR, '暂无预约权限');
            }
        }

        $prepayPrice = CommunityService::getInstance()->getCommunityConfig('prepay_price');
        $orderNo = getNo('PR');
        $createAt = date('Y-m-d H:i:s');
        $data = [
            'user_id' => $this->userinfo->id,
            'order_no' => $orderNo,
            'pay_price' => $prepayPrice,
            'status' => 1,
            'create_at' => $createAt,
        ];
        $orderId = PrepayCommunityOrder::getInstance()->insertGetId($data);
        //取消订单
        RabbitMqService::sendDelay(['type' => 'community_prepay_order', 'order_id' => $orderId], 60);
        //保存订单信息
        RedisCache::setEx(KeysUtil::getCommunityOrderKey($data['order_no']), 60, json_encode($data));
        $userFinance = MemberService::getInstance()->finance($this->userinfo->id);
        $userBag = CommunityService::getInstance()->getUserBag($this->userinfo->id);
        return [
            'orderInfo' => ['orderId' => $orderId, 'orderNo' => $orderNo, 'createAt' => $createAt],
            'communityAmount' => $userFinance['amount'],
            'payPrice' => $prepayPrice,
            'bagAmount' => !empty($userBag['communityAmount']) ? $userBag['communityAmount'] : 0,
        ];
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function prepayOrder($orderNo, $isBag, $type, $payPassword, $paySubType): array
    {
        if (!RedLock::getInstance()->lock('prepayOrder:' . $orderNo, 1)) {
            CommonUtil::throwException(ErrorConst::FREQUENT_ERROR, ErrorConst::FREQUENT_ERROR_MSG);
        }

        $switch = CommunityService::getInstance()->getCommunityConfig('prepay_status');
        if ($switch == 0) {
            CommonUtil::throwException(ErrorConst::FREQUENT_ERROR, '该功能暂时未开放');
        }

        //获取订单
        //$orderInfo = CommunityService::getInstance()->getOrder($orderNo);
        $orderInfo = RedisCache::get(KeysUtil::getCommunityOrderKey($orderNo));
        $orderInfo = $orderInfo ? json_decode($orderInfo, true) : [];

        //订单不存在 订单状态错误      订单用户id错误 ，订单时间超时
        if (empty($orderInfo) || $orderInfo['status'] != 1 || $orderInfo['user_id'] != $this->userinfo->id) {
            CommonUtil::throwException(ErrorConst::NO_ORDER_ERROR, ErrorConst::NO_ORDER_ERROR_MSG);
        }

        if ($type == 3) {
            $account = MemberService::getInstance()->account($this->userinfo->id);
            if (empty($account)) {
                CommonUtil::throwException(ErrorConst::NO_PAY_PASSWORD_ERROR, ErrorConst::NO_PAY_PASSWORD_ERROR_MSG);
            }

            //验证支付密码
            if ($account['payPwd'] != $payPassword) {
                CommonUtil::throwException(ErrorConst::PAY_PASSWORD_ERROR, ErrorConst::PAY_PASSWORD_ERROR_MSG);
            }
        }

        $amountPrice = 0;
        $signPrice = 0;
        //获取余额
        if ($type == 3) {
            $userBalance = MemberService::getInstance()->finance($this->userinfo->id);
            $amountPrice = $userBalance['amount'];
        }
        //获取红包
        if ($isBag) {
            $userBag = CommunityService::getInstance()->getUserBag($this->userinfo->id);
            $signPrice = $userBag['communityAmount'] ?? 0;
        }

        $price = $orderInfo['pay_price'];
        $payPrice = bcsub($price, $signPrice, 2);
        $isBalance = 0;
        if ($type == 3 && $amountPrice < $payPrice) {
            CommonUtil::throwException(ErrorConst::NO_PRICE_ERROR, ErrorConst::NO_PRICE_ERROR_MSG);
        }
        if ($type == 3) {
            //社区余额
            $amountPrice = $payPrice;
            $thirdPayPrice = 0;
            $isBalance = 1;
        } else {
            $thirdPayPrice = $payPrice;
        }

        PrepayCommunityOrder::getInstance()->where('order_no', $orderNo)->update(['pay_type' => $type]);
        $payInfo = CommunityService::getInstance()->payOrder($orderInfo, $thirdPayPrice, $amountPrice, $signPrice, $type, 9);
        if (!$payInfo) {
            CommonUtil::throwException(ErrorConst::SYSTEM_ERROR, ErrorConst::SYSTEM_ERROR_MSG);
        }
        //有微信支付
        //$userInfo = MemberService::getInstance()->getUserInfo($this->userinfo->id);
        $userInfo = RedisCache::hGetAll(KeysUtil::getMemberInfoKey($this->userinfo->id));
        $pay = [];
        if ($isBalance) {
            //余额全付
            $info = [
                'pay_status' => 3,
                'pay_no' => $payInfo['pay_no'],
                'money' => $payInfo['community_pay_amount'],
                'trade_no' => '',
                'receipt_data' => '',
            ];

            //$info = PayService::getInstance()->payFormOrder($info);
            $event["exchange"] = config('rabbitmq.order_callback_queue');
            RabbitMqService::send($event, $info);
            if (!$info) {
                CommonUtil::throwException(ErrorConst::SYSTEM_ERROR, ErrorConst::SYSTEM_ERROR_MSG);
            }
        } elseif ($type == 4) {
            //杉德支付
            $ret = SandLogic::getInstance()->accountBalanceQuery($userInfo['id']);
            if (empty($ret)) {
                CommonUtil::throwException(ErrorConst::PARAM_ERROR, '个人钱包未开户');
            }
            if (env('test.is_test') == 1) {
                if ($ret['accountList'][0]['availableBal'] < 0.01) {
                    CommonUtil::throwException(ErrorConst::NO_PRICE_ERROR, ErrorConst::NO_PRICE_ERROR_MSG);
                }
            } else {
                if ($ret['accountList'][0]['availableBal'] < $thirdPayPrice) {
                    CommonUtil::throwException(ErrorConst::NO_PRICE_ERROR, ErrorConst::NO_PRICE_ERROR_MSG);
                }
            }
            Log::info($orderInfo['order_no'] . 'prepayOrder：支付金额：' . $thirdPayPrice);
            if (env('test.is_test') == 1) {
                $thirdPayPrice = 0.01;
            }
            $pay = SandLogic::getInstance()->orderCreate($this->userinfo->id, $thirdPayPrice, $payInfo['pay_no']);
        } else {
            $pay = PayService::getInstance()->toPay($payInfo, $userInfo, $type, $paySubType);
        }

        return ['payInfo' => $pay, 'isBalance' => $isBalance];
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function prepayInfo(): array
    {
        /*if (!RedLock::getInstance()->lock('prepayInfo:' . $this->userinfo->id . ':' . request()->ip(), 2)) {
            CommonUtil::throwException(ErrorConst::FREQUENT_ERROR, ErrorConst::FREQUENT_ERROR_MSG);
        }*/

        $prepayTime = CommunityService::getInstance()->getCommunityConfig('prepay_time');
        if (empty($prepayTime)) {
            CommonUtil::throwException(ErrorConst::FREQUENT_ERROR, '预约时间不能为空');
        }
        $status = CommunityService::getInstance()->getCommunityConfig('prepay_status');
        list($start, $end) = explode('-', $prepayTime);
        $now = date('H:i');
        if($now < $start || $now > $end){
            return ['status' => 0,'time' => $prepayTime, 'switch' => $status, 'msg' => '预约未开始，请稍后再来','btnName' => '预约未开始'];
            //CommonUtil::throwException(ErrorConst::FREQUENT_ERROR, '未到预约时间');
        }

        //每人每天可抢次数
        $prepayEveryCount = CommunityService::getInstance()->getCommunityConfig('prepay_every_count');
        $where = [
            ['user_id','=',$this->userinfo->id],
            ['status','in',[1,2]],
            ['create_at','>=',date('Y-m-d')]
        ];
        $userCount = PrepayCommunityOrder::getInstance()->where($where)->count();
        if($userCount >= $prepayEveryCount){
            return ['status' => 0,'time' => $prepayTime, 'switch' => $status, 'msg' => '今天已预约社区','btnName' => '已预约'];
        }

        //预付数量
        $prepayNum = CommunityService::getInstance()->getCommunityConfig('prepay_num');
        $where = [
            ['status','in',[1,2]],
            ['create_at','>=',date('Y-m-d')]
        ];
        $count = PrepayCommunityOrder::getInstance()->where($where)->count();
        if($count >= $prepayNum){
            //CommonUtil::throwException(ErrorConst::FREQUENT_ERROR, '可抢次数已用完');
            return ['status' => 0,'time' => $prepayTime, 'switch' => $status,'msg' => '暂无预约次数','btnName' => '预约已结束'];
        }

        //入门门槛
        $prepayJoinNum = CommunityService::getInstance()->getCommunityConfig('prepay_join_num');
        if($prepayJoinNum > 0){
            $where = [
                ['user_id','=',$this->userinfo->id],
                ['status','=',2]
            ];
            $count = CommunityOrder::getInstance()->where($where)->count();
            if($count > $prepayJoinNum){
                return ['status' => 0,'time' => $prepayTime, 'switch' => $status,'msg' => '暂无预约权限','btnName' => '暂无预约权限'];
            }
        }
        return ['status' => 1,'time' => $prepayTime, 'switch' => $status,'msg' => 'success','btnName' => 'success'];
    }

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function prepayList($page, $pageSize): array
    {
        $where = [
            ['user_id', '=', $this->userinfo->id],
            ['deleted', '=', 0]
        ];
        $data = PrepayCommunityOrder::getInstance()
            ->where($where)
            ->order('id desc')
            ->page($page, $pageSize)
            ->select();
        return ['rows' => $data];
    }

    public function prepayDel(): bool
    {
        $where = [
            ['user_id', '=', $this->userinfo->id]
        ];
        $data = [
            'deleted' => 1,
            'update_at' => date('Y-m-d H:i:s')
        ];
        PrepayCommunityOrder::getInstance()->where($where)->update($data);
        return true;
    }

    /**
     * @param $communityId
     * @param $image
     * @param $signImage
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function createCommunityOrder($communityId, $image, $signImage): array
    {
        if (!RedLock::getInstance()->lock('createCommunityOrder:' . $this->userinfo->id . ':' . request()->ip(), 2)) {
            CommonUtil::throwException(ErrorConst::FREQUENT_ERROR, ErrorConst::FREQUENT_ERROR_MSG);
        }

        //支付中的订单
        $inPayUserId = RedisCache::get(KeysUtil::getCommunityInPayOrderKey($communityId));
        if ($inPayUserId && $inPayUserId != $this->userinfo->id) {
            CommonUtil::throwException(ErrorConst::COMMUNITY_IN_PAY_ERROR, ErrorConst::COMMUNITY_IN_PAY_ERROR_MSG);
        }

        //抢购次数
        $canRush = CommunityService::getInstance()->userCanRush($this->userinfo->id);
        if (!$canRush) {
            CommonUtil::throwException(ErrorConst::CAN_RUSH_ERROR, ErrorConst::CAN_RUSH_ERROR_MSG);
        }

        //限制抢购次数
        $member = Member::getInstance()->where('id', $this->userinfo->id)->field('limit_count')->find();
        $where = [
            ['user_id', '=', $this->userinfo->id],
            ['status', 'in', [CommunityConst::ORDER_NO_PAY, CommunityConst::ORDER_PAY]],
            ['create_at', '>=', date('Y-m-d')]
        ];
        $count = CommunityOrder::getInstance()->where($where)->count();
        if ($member['limitCount'] > 0 && $count >= $member['limitCount']) {
            CommonUtil::throwException(ErrorConst::COMMUNITY_IN_PAY_ERROR, ErrorConst::COMMUNITY_IN_PAY_ERROR_MSG);
        }

        //占位中
        $seconds = 15;
        $seizeUserId = RedisCache::get(KeysUtil::getCommunitySeizeKey($communityId));
        if ($seizeUserId && $seizeUserId != $this->userinfo->id) {
            CommonUtil::throwException(ErrorConst::COMMUNITY_IN_PAY_ERROR, ErrorConst::COMMUNITY_IN_PAY_ERROR_MSG);
        }
        RedisCache::setEx(KeysUtil::getCommunitySeizeKey($communityId), $seconds, $this->userinfo->id);

        $communityInfo = RedisCache::hGetAll(KeysUtil::getCommunityInfo($communityId));
        if (empty($communityInfo)) {
            CommonUtil::throwException(ErrorConst::NO_COMMUNITY_ERROR, ErrorConst::NO_COMMUNITY_ERROR_MSG);
        }
        if ($communityInfo['type'] == CommunityConst::TYPE_TWO) {
            //会议
            $meetTime = RedisCache::get(KeysUtil::getCommunityMeetTimeKey());
            $time = CommunityService::getInstance()->getTimeInfo([$meetTime]);
        } else {
            $time = CommunityService::getInstance()->getTimes();
        }
        if (!$time['inPay']) {
            CommonUtil::throwException(ErrorConst::COMMUNITY_IN_NOT_ERROR, ErrorConst::COMMUNITY_IN_NOT_MSG);
        }

        //社区状态错误
        /*$communityUser = RedisCache::hGetAll(KeysUtil::getCommunityInfo($communityId));
        if (!in_array($communityUser['community_status'], [CommunityConst::CAN_STATUS, CommunityConst::RELEASE_STATUS])) {
            CommonUtil::throwException(ErrorConst::NO_COMMUNITY_ERROR, ErrorConst::NO_COMMUNITY_ERROR_MSG);
        }*/
        $communityUser = CommunityUser::getInstance()->where('community_id', $communityId)->find();
        if (!in_array($communityUser['communityStatus'], [CommunityConst::CAN_STATUS, CommunityConst::RELEASE_STATUS])) {
            CommonUtil::throwException(ErrorConst::COMMUNITY_IN_PAY_ERROR, ErrorConst::COMMUNITY_IN_PAY_ERROR_MSG);
        }

        //新人专区是否是新手
        $isNew = CommunityService::getInstance()->isNew($this->userinfo->id);
        if (!$isNew && $communityUser['type'] == 1) {
            CommonUtil::throwException(ErrorConst::NEW_COUNT_ERROR, ErrorConst::NEW_COUNT_ERROR_MSG);
        }

        //获取下次应该展示的用户数据
        $communityInfo = $this->getCommunityNextInfo($communityId);
        //获取上次订单
        $lastOrder = CommunityService::getInstance()->getLastCommunityOrder($communityUser['last_order_id']);

        $orderInfo = CommunityService::getInstance()->createOrder($communityInfo, $this->userinfo->id, $lastOrder, $image, $signImage);
        if (!$orderInfo) {
            CommonUtil::throwException(ErrorConst::SYSTEM_ERROR, ErrorConst::SYSTEM_ERROR_MSG);
        }
        $userFinance = MemberService::getInstance()->finance($this->userinfo->id);
        $userBag = CommunityService::getInstance()->getUserBag($this->userinfo->id);
        return [
            'orderInfo' => $orderInfo,
            'communityAmount' => $userFinance['amount'],
            'bagAmount' => !empty($userBag['communityAmount']) ? $userBag['communityAmount'] : 0,
        ];
    }

    /**
     * @param $communityId
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function communityOrderPreview($communityId): array
    {
        if (!RedLock::getInstance()->lock('communityOrderPreview:' . $this->userinfo->id . ':' . request()->ip(), 1)) {
            CommonUtil::throwException(ErrorConst::FREQUENT_ERROR, ErrorConst::FREQUENT_ERROR_MSG);
        }
        //统计用户社区点击数
        $device = request()->header('romName', '');
        $event["exchange"] = config('rabbitmq.info_queue');
        RabbitMqService::send($event, ['type' => 'member_click', 'data' => ['id' => $this->userinfo->id, 'device' => $device, 'phone' => $this->userinfo->phone]]);

        $account = MemberAccountCache::getKeyData($this->userinfo->id);
        if (empty($account) || $account['is_active_sd'] != 1) {
            CommonUtil::throwException(ErrorConst::SAND_NO_BIND_ERROR, ErrorConst::SAND_NO_BIND_ERROR_MSG);
        }

        $communityInfo = RedisCache::hGetAll(KeysUtil::getCommunityInfo($communityId));
        if (empty($communityInfo)) {
            CommonUtil::throwException(ErrorConst::NO_COMMUNITY_ERROR, ErrorConst::NO_COMMUNITY_ERROR_MSG);
        }

        if ($communityInfo['type'] != 4) {
            $where = [
                ['status', '=', 2],
                ['is_turn', '=', 0],
                ['is_final', '=', 0],
                ['user_id', '=', $this->userinfo->id]
            ];
            $prepayCount = PrepayCommunityOrder::getInstance()->where($where)->count();
            if ($prepayCount > 0) {
                CommonUtil::throwException(ErrorConst::PARAM_ERROR, '请先支付预约订单');
            }
        }

        //不能抢自己的社区
        if ($communityInfo['user_id'] == $this->userinfo->id) {
            CommonUtil::throwException(ErrorConst::BUY_NOT_MYSELF_ERROR, ErrorConst::BUY_NOT_MYSELF_ERROR_MSG);
        }

        //社区存在支付订单
        $inPayUserId = RedisCache::get(KeysUtil::getCommunityInPayOrderKey($communityId));
        if ($inPayUserId && $inPayUserId != $this->userinfo->id) {
            CommonUtil::throwException(ErrorConst::COMMUNITY_IN_PAY_ERROR, ErrorConst::COMMUNITY_IN_PAY_ERROR_MSG);
        }
        //用户存在支付订单
        $inPayUserId = RedisCache::get(KeysUtil::getCommunityUserInPayOrderKey($this->userinfo->id));
        if ($inPayUserId) {
            CommonUtil::throwException(ErrorConst::COMMUNITY_PAY_IN_ERROR, ErrorConst::COMMUNITY_PAY_IN_ERROR_MSG);
        }
        //抢购次数
        $canRush = CommunityService::getInstance()->userCanRush($this->userinfo->id);
        if (!$canRush) {
            CommonUtil::throwException(ErrorConst::CAN_RUSH_ERROR, ErrorConst::CAN_RUSH_ERROR_MSG);
        }

        $buyStatus = Member::getInstance()->where('id',$this->userinfo->id)->value('buy_status');
        if($buyStatus == 0){
            $ret = CommunityService::getInstance()->actionCount($this->userinfo->id);
            if(!$ret){
                CommonUtil::throwException(ErrorConst::CAN_RUSH_ERROR, '暂无抢购次数');
            }
        }

        if($communityInfo['type'] != 4){
            $where = [
                ['status','=',2],
                ['is_turn','=',0],
                ['is_final','=',0],
                ['user_id','=',$this->userinfo->id]
            ];
            $prepayCount = PrepayCommunityOrder::getInstance()->where($where)->count();
            if($prepayCount > 0){
                CommonUtil::throwException(ErrorConst::PARAM_ERROR, '请先支付预约订单');
            }

            //抢购概率
            $randomNumber = mt_rand(1, 100);
            $member = Member::getInstance()->where('id',$this->userinfo->id)->field('win_rate,limit_count')->find();
            if($randomNumber > $member['winRate']){
                CommonUtil::throwException(ErrorConst::COMMUNITY_IN_PAY_ERROR, ErrorConst::COMMUNITY_IN_PAY_ERROR_MSG);
            }

            //限制换购次数
            $where = [
                ['user_id','=',$this->userinfo->id],
                ['status','in',[CommunityConst::ORDER_NO_PAY,CommunityConst::ORDER_PAY]],
                ['create_at','>=',date('Y-m-d')]
            ];
            $count = CommunityOrder::getInstance()->where($where)->count();
            if($member['limitCount'] > 0 && $count >= $member['limitCount']){
                CommonUtil::throwException(ErrorConst::COMMUNITY_IN_PAY_ERROR, ErrorConst::COMMUNITY_IN_PAY_ERROR_MSG);
            }
        }


        if ($communityInfo['type'] == 4) {
            $where = [
                ['status', '=', 2],
                ['community_id', '=', $communityId],
                ['update_at', '>=', date('Y-m-d')]
            ];
            $prepayOrder = PrepayCommunityOrder::getInstance()->where($where)->find();
            if (empty($prepayOrder)) {
                CommonUtil::throwException(ErrorConst::PARAM_ERROR, '请提前预约社区');
            }
        }

        //社区状态错误
        if (!in_array($communityInfo['community_status'], [CommunityConst::CAN_STATUS, CommunityConst::RELEASE_STATUS])) {
            CommonUtil::throwException(ErrorConst::COMMUNITY_IN_PAY_ERROR, ErrorConst::COMMUNITY_IN_PAY_ERROR_MSG);
        }

        //占位中
        $seconds = 15;
        $seizeUserId = RedisCache::get(KeysUtil::getCommunitySeizeKey($communityId));
        if ($seizeUserId && $seizeUserId != $this->userinfo->id) {
            CommonUtil::throwException(ErrorConst::COMMUNITY_IN_PAY_ERROR, ErrorConst::COMMUNITY_IN_PAY_ERROR_MSG);
        }
        RedisCache::setEx(KeysUtil::getCommunitySeizeKey($communityId), $seconds, $this->userinfo->id);

        if ($communityInfo['type'] == CommunityConst::TYPE_TWO) {
            //会议
            $meetTime = RedisCache::get(KeysUtil::getCommunityMeetTimeKey());
            $time = CommunityService::getInstance()->getTimeInfo([$meetTime]);
        } else {
            $time = CommunityService::getInstance()->getTimes();
        }
        if (!$time['inPay']) {
            CommonUtil::throwException(ErrorConst::COMMUNITY_IN_NOT_ERROR, ErrorConst::COMMUNITY_IN_NOT_MSG);
        }

        $communityInfo = $this->getCommunityNextInfo($communityId);
        //新人参与人数
        $isNew = CommunityService::getInstance()->isNew($this->userinfo->id);
        if (!$isNew && $communityInfo['type'] == 1) {
            CommonUtil::throwException(ErrorConst::NEW_COUNT_ERROR, ErrorConst::NEW_COUNT_ERROR_MSG);
        }

        $data['rule'] = SysLogic::getInstance()->article(5);
        $communityInfo['img'] = '';
        $data['community'] = $communityInfo;
        $data['seconds'] = $seconds;
        $data['goods'] = CommunityService::getInstance()->getCommunityGoods();
        $data['prepayPrice'] = CommunityService::getInstance()->getPrepayPrice($communityId, $this->userinfo->id);
        return $data;
    }

    /**
     * @param $page
     * @param $pageSize
     * @param $type
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function communityPayList($page, $pageSize, $type): array
    {
        $start = ($page - 1) * $pageSize;
        $end = $start + $pageSize - 1;
        if ($type == 4) {
            $end = 1000;
        }
        $list = RedisCache::zRevRange(KeysUtil::getCommunityPayListKey($type), $start, $end, true);
        $data = [];
        foreach ($list as $k => $v) {
            $communityInfo = RedisCache::hGetAll(KeysUtil::getCommunityInfo($k));
            if (empty($communityInfo)) {
                continue;
            }
            $data = $this->getArr($communityInfo, $data);
        }
        if ($type == 1) {
            //新人参与人数
            $isNew = CommunityService::getInstance()->isNew($this->userinfo->id);
            if (!$isNew) {
                CommonUtil::throwException(ErrorConst::NEW_COUNT_ERROR, ErrorConst::NEW_COUNT_ERROR_MSG);
            }
        }

        $time = CommunityService::getInstance()->getTimes();
        if (!$time['inPay']) {
            $data = [];
        }
        $prepayTimeout = (int)CommunityService::getInstance()->getCommunityConfig('prepay_timeout') ?: 0;
        //新人专区超时，社区转换到广场专区
        if (!empty($data)) {
            $getCommunityNewLockKey = RedisCache::get(KeysUtil::getCommunityNewLockKey());
            if (!$getCommunityNewLockKey) {
                $rabbitmqData = ['type' => 'community_new'];
                RabbitMqService::sendDelay($rabbitmqData, 60);
                RedisCache::setEx(KeysUtil::getCommunityNewLockKey(), 60, 1);
            }

            $getCommunityPrepayLockKey = RedisCache::get(KeysUtil::getCommunityPrepayLockKey());
            if (!$getCommunityPrepayLockKey) {
                $rabbitmqData = ['type' => 'community_prepay'];
                if ($prepayTimeout > 0) {
                    RabbitMqService::sendDelay($rabbitmqData, $prepayTimeout * 60);
                    RedisCache::setEx(KeysUtil::getCommunityPrepayLockKey(), $prepayTimeout * 60, 1);
                }
            }

            if ($type == 4) {
                //只显示自己的预约社区
                $newData = [];
                foreach ($data as $v) {
                    $where = [
                        ['status', '=', 2],
                        ['user_id', '=', $this->userinfo->id],
                        ['is_final', '=', 0],
                        ['is_refund', '=', 0],
                        ['community_id', '=', $v['communityId']]
                    ];
                    $communityIds = PrepayCommunityOrder::getInstance()->where($where)->find();
                    if (empty($communityIds)) {
                        continue;
                    }
                    $newData[] = $v;
                }
                if (!empty($newData)) {
                    $data = $newData;
                } else {
                    $data = [];
                }
            }
        }

        //预付倒计时
        $start = date('Y-m-d H:i:s', strtotime($time['start']));
        $end = date('H:i', strtotime("+{$prepayTimeout} minutes", strtotime($start)));
        return ['rows' => $data, 'time' => $time, 'prepayTimeout' => $end];
    }

    public function meetPayList($page, $pageSize, $password): array
    {
        if (empty($password)) {
            CommonUtil::throwException(ErrorConst::PASSWORD_EMPTY_ERROR, ErrorConst::PASSWORD_EMPTY_ERROR_MSG);
        }
        $start = ($page - 1) * $pageSize;
        $end = $start + $pageSize - 1;
        $activityList = RedisCache::zRevRange(keysUtil::getCommunityActivityListKey(date('Y-m-d')), 0, -1, true);
        if (empty($activityList)) {
            CommonUtil::throwException(ErrorConst::PASSWORD_ERROR, ErrorConst::PASSWORD_ERROR_MSG);
        }
        $matchPass = 0;
        $activityData = [];
        foreach ($activityList as $k => $v) {
            $activity = RedisCache::hGetAll(KeysUtil::getCommunityActivityKey($k));
            if (empty($activity)) {
                continue;
            }
            if ($activity['password'] != $password) {
                continue;
            }
            $matchPass = 1;
            $activityData = $activity;
            break;
        }
        //密码错误
        if (!$matchPass) {
            CommonUtil::throwException(ErrorConst::PASSWORD_ERROR, ErrorConst::PASSWORD_ERROR_MSG);
        }

        //未设置时间
        if (empty($activityData['open_time'])) {
            CommonUtil::throwException(ErrorConst::MEETING_NO_TIME_ERROR, ErrorConst::MEETING_NO_TIME_ERROR_MSG);
        }

        //判断状态
        if ($activityData['status'] != 1) {
            CommonUtil::throwException(ErrorConst::MEETING_NO_START_ERROR, ErrorConst::MEETING_NO_START_ERROR_MSG);
        }

        //会议未开始
        list($startTime, $endTime) = explode('-', $activityData['open_time']);
        $now = date('H:i');
        if ($now < $startTime) {
            CommonUtil::throwException(ErrorConst::MEETING_NO_START_ERROR, ErrorConst::MEETING_NO_START_ERROR_MSG);
        }

        //会议已结束
        if ($endTime && date('H:i') > $endTime) {
            CommonUtil::throwException(ErrorConst::MEETING_END_ERROR, ErrorConst::MEETING_END_ERROR_MSG);
        }

        //该场会议所有社区已被竞拍完
        $count = RedisCache::zCard(KeysUtil::getCommunityMeetListKey($activityData['id']));
        if ($count <= 0) {
            CommonUtil::throwException(ErrorConst::MEETING_FINISH_ERROR, ErrorConst::MEETING_FINISH_ERROR_MSG);
        }

        //入门门槛
        if (!empty($activityData['is_join']) && !empty($activityData['join_num'])) {
            $where = [
                ['user_id', '=', $this->userinfo->id],
                ['status', '=', 2],
            ];
            $count = CommunityOrder::getInstance()->where($where)->count();
            if ($count > $activityData['join_num']) {
                CommonUtil::throwException(ErrorConst::MEETING_FINISH_ERROR, '暂无权限参与本会场');
            }
        }

        $list = RedisCache::zRevRange(KeysUtil::getCommunityMeetListKey($activityData['id']), $start, $end);
        $data = [];
        foreach ($list as $v) {
            $communityInfo = RedisCache::hGetAll(KeysUtil::getCommunityInfo($v));
            $data = $this->getArr($communityInfo, $data);
        }
        //保存会议时间并设置过期时间
        //if (!RedisCache::get(KeysUtil::getCommunityMeetTimeKey())) {
        RedisCache::set(KeysUtil::getCommunityMeetTimeKey(), $activityData['open_time'], strtotime(date("Y-m-d {$endTime}")));
        //}
        $time = CommunityService::getInstance()->getTimeInfo([$activityData['open_time']]);
        return ['rows' => $data, 'time' => $time];
    }

    public function packetList($page, $pageSize): array
    {
        $where = [
            ['user_id', '=', $this->userinfo->id],
            ['order_status', '=', 2],
            ['sign_status', '=', 1],
            ['expire_at', '>', date('Y-m-d H:i:s')],
        ];
        $packetList = CommunitySignUser::getInstance()
            ->where($where)
            ->limit(($page - 1) * $pageSize, $pageSize)
            ->order('id desc')
            ->select();
        $packetList = empty($packetList) ? [] : $packetList->toArray();
        $rows = [];
        $packetAmount = 0;
        foreach ($packetList as $val) {
            $rows[] = [
                'amount' => $val['communityAmount'],
                'remark' => '社区签到',
                'createAt' => $val['createAt'],
            ];
            $packetAmount += $val['communityAmount'];
        }
        return [
            'rows' => $rows,
            'packetAmount' => $packetAmount,
        ];
    }

    /**
     * @param $type
     * @param $page
     * @param $pageSize
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function withdrawAmountList($type, $page, $pageSize): array
    {
        $where = [
            ['user_id', '=', $this->userinfo->id],
        ];
        if ($type) {
            $where[] = ['type', '=', $type];
        }
        $list = MemberWithdraw::getInstance()
            ->where($where)
            ->order('id desc')
            ->page($page, $pageSize)
            ->select();
        $list = empty($list) ? [] : $list->toArray();
        foreach ($list as &$v) {
            $v['typeName'] = '提现到' . CommunityService::getInstance()->getTypeName($v['type']);
            $v['remark'] = $v['notes'] ?: $v['remark'];
        }

        $allWithdraw = MemberWithdraw::getInstance()
            ->where(['user_id' => $this->userinfo->id])
            ->sum('amount');

        //提现成功
        $successWithdraw = MemberWithdraw::getInstance()
            ->where(['user_id' => $this->userinfo->id, 'status' => 1])
            ->sum('amount');
        //提现驳回
        $errorWithdraw = MemberWithdraw::getInstance()
            ->where(['user_id' => $this->userinfo->id, 'status' => 2])
            ->sum('amount');

        return [
            'rows' => $list,
            'allWithdraw' => $allWithdraw,
            'successWithdraw' => $successWithdraw,
            'errorWithdraw' => $errorWithdraw,
        ];
    }

    /**
     * @param $type
     * @param $page
     * @param $pageSize
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function withdrawList($type, $page, $pageSize): array
    {
        $where = [
            'user_id' => $this->userinfo->id,
            'type' => $type,
        ];
        $list = CommunityWithdraw::getInstance()
            ->where($where)
            ->order('id desc')
            ->page($page, $pageSize)
            ->select();
        $list = empty($list) ? [] : $list->toArray();

        $withdraw = CommunityWithdraw::getInstance()
            ->field('sum(amount) as all_withdraw,
            sum(if(status=1,amount,0)) as success_withdraw,
            sum(if(status=2,amount,0)) as error_withdraw')
            ->where($where)
            ->find();

        return [
            'rows' => $list,
            'allWithdraw' => bcadd($withdraw['allWithdraw'], 0, 4),
            'successWithdraw' => bcadd($withdraw['successWithdraw'], 0, 4),
            'errorWithdraw' => bcadd($withdraw['errorWithdraw'], 0, 4),
        ];
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function withdrawInfo($type): array
    {
        $userData = MemberService::getInstance()->getUserInfo($this->userinfo->id);
        if (empty($userData)) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }
        if (empty($userData['phone'])) {
            CommonUtil::throwException(ErrorConst::PHONE_NOT_EXIST, ErrorConst::PHONE_NOT_EXIST_MSG);
        }
        $finance = MemberService::getInstance()->finance($this->userinfo->id);
        //$communityAmount = $userAdmin['community_amount'] ?? $userAdmin['communityAmount'];
        $arr = [
            0 => $finance['communityAmount'],
            1 => $finance['giftBagAmount'],
            2 => $finance['inviteAmount'],
            3 => $finance['bonus'],
        ];
        $communityAmount = $arr[$type] ?? '0.00';
        //$percent = ValConst::COMMUNITY_WITHDRAW_CHARGE_PERCENT;
        //$percent = CommunityService::getInstance()->getCommunityConfig('earnings_percent');

        $withdrawType = [
            0 => 'greenpoints',
            1 => 'packspoints',
            2 => 'commission',
            3 => 'bonus',
        ];
        $percent = 0;
        $communityDeductionRate = 0;
        $configSet = MemberInfoService::getInstance()->withdrawConfig($withdrawType[$type]);
        if(!empty($configSet) && $configSet['status'] == 1){
            $percent = $configSet['premium'];
            $communityDeductionRate = $configSet['community_deduction_rate'];
        }
        $rate = bcsub(100,$percent+$communityDeductionRate,2);
        if($percent > 0){
            $communityMsg = [
                '1.团队收益提现到个人余额 ',
                '2.提现到余额手续' . $percent . '%的手续费',
                //'3.提现'. $rate .'%到余额，'. $communityDeductionRate . '%到平台抵扣券',
                '3.绿色积分提现，20%~50%到平台抵扣券，用于平台消费抵扣',
            ];
        }else{
            $communityMsg = [
                '1.团队收益提现到个人余额 ',
                //'2.提现'. $rate .'%到余额，'. $communityDeductionRate . '%到平台抵扣券',
                '2.绿色积分提现，20%~50%到平台抵扣券，用于平台消费抵扣',
            ];
        }


        return ['phone' => $userData['phone'], 'communityAmount' => $communityAmount, 'communityMsg' => $communityMsg, 'fee' => $percent,'communityDeductionRate' => $communityDeductionRate];
    }

    /**
     * @param $code
     * @param $amount
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function withdrawCommunity($payPassword, $amount, $type): bool
    {
        if (!RedLock::getInstance()->lock('withdrawCommunity_' . $this->userinfo->id, 1)) {
            CommonUtil::throwException(ErrorConst::FREQUENT_ERROR, ErrorConst::FREQUENT_ERROR_MSG);
        }
        if (!in_array($type, [0, 1, 2, 3])) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }
        if (empty($payPassword) || $amount < 0) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }
        $account = MemberService::getInstance()->account($this->userinfo->id);
        if (empty($account)) {
            CommonUtil::throwException(ErrorConst::NO_PAY_PASSWORD_ERROR, ErrorConst::NO_PAY_PASSWORD_ERROR_MSG);
        }

        //验证支付密码
        if ($account['payPwd'] != $payPassword) {
            CommonUtil::throwException(ErrorConst::PAY_PASSWORD_ERROR, ErrorConst::PAY_PASSWORD_ERROR_MSG);
        }

        $finance = MemberService::getInstance()->finance($this->userinfo->id);

        $arr = [
            0 => $finance['communityAmount'],
            1 => $finance['giftBagAmount'],
            2 => $finance['inviteAmount'],
            3 => $finance['bonus'],
        ];

        $financeMoney = $arr[$type];
        if ($financeMoney < $amount) {
            CommonUtil::throwException(ErrorConst::NO_PRICE_ERROR, ErrorConst::NO_PRICE_ERROR_MSG);
        }

        $withdrawType = [
            0 => 'greenpoints',
            1 => 'packspoints',
            2 => 'commission',
            3 => 'bonus',
        ];
        $configSet = MemberInfoService::getInstance()->withdrawConfig($withdrawType[$type]);
        if(isset($configSet['status']) && $configSet['status'] != 1) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, '未开启提现');
        }
        if(!empty($configSet)){
            if($configSet['status'] == 1){
                if($amount < $configSet['min_amount']){
                    CommonUtil::throwException(ErrorConst::PARAM_ERROR, '最小提现金额'.$configSet['min_amount'].'元');
                }
                if($amount > $configSet['max_amount']){
                    CommonUtil::throwException(ErrorConst::PARAM_ERROR, '最高提现金额'.$configSet['max_amount'].'元');
                }
                $where = [
                    ['user_id','=',$this->userinfo->id],
                    ['type','=',$type],
                    ['status','=',2],
                    ['log_type','=','community_withdraw'],
                    ['create_at','>=',date('Y-m-d')]
                ];
                $count = MemberCommunityAmountLog::getInstance()->where($where)->count();
                if($count > $configSet['times']){
                    CommonUtil::throwException(ErrorConst::PARAM_ERROR, '今日提现次数已用完');
                }
            }
        }

        $return = CommunityService::getInstance()->withdrawCommunity($this->userinfo->id, $amount, $type);
        if (!$return) {
            CommonUtil::throwException(ErrorConst::WITHDRAW_ERROR, ErrorConst::WITHDRAW_ERROR_MSG);
        }
        return true;
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function withdraw($payPassword, $amount, $type): bool
    {
        if (!RedLock::getInstance()->lock('withdraw_' . $this->userinfo->id, 1)) {
            CommonUtil::throwException(ErrorConst::FREQUENT_ERROR, ErrorConst::FREQUENT_ERROR_MSG);
        }

        if(!in_array($type,[2,3])){
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }

        if (empty($payPassword) || $amount < 0) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }

        $account = MemberService::getInstance()->account($this->userinfo->id);
        if (empty($account)) {
            CommonUtil::throwException(ErrorConst::NO_PAY_PASSWORD_ERROR, ErrorConst::NO_PAY_PASSWORD_ERROR_MSG);
        }

        if ($type == 2 && empty($account['aliAccount'])) {
            CommonUtil::throwException(ErrorConst::NO_BIND_ALIPAY_ERROR, ErrorConst::NO_BIND_ALIPAY_ERROR_MSG);
        }

        //验证支付密码
        if ($account['payPwd'] != $payPassword) {
            CommonUtil::throwException(ErrorConst::PAY_PASSWORD_ERROR, ErrorConst::PAY_PASSWORD_ERROR_MSG);
        }

        $finance = MemberService::getInstance()->finance($this->userinfo->id);
        if ($finance['amount'] < $amount) {
            CommonUtil::throwException(ErrorConst::NO_PRICE_ERROR, ErrorConst::NO_PRICE_ERROR_MSG);
        }
        $withdrawSecondToMoney = 0;
        $configSet = MemberInfoService::getInstance()->withdrawConfig('balance');
        if(empty($configSet)){
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, '未配置');
        }
        if($configSet['status'] == 0){
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, '提现已关闭');
        }
        if(!empty($configSet) && $configSet['status'] == 1){
            //每次最大提现金额
            //$withdrawMaxMoneyLimit = CommunityService::getInstance()->getCommunityConfig('withdraw_max_money_limit');
            if ($amount > $configSet['max_amount']) {
                CommonUtil::throwException(ErrorConst::WITHDRAW_MAX_MONEY_LIMIT_ERROR, ErrorConst::WITHDRAW_MAX_MONEY_LIMIT_ERROR_MSG . $configSet['max_amount'] . '元');
            }
            //每次最小提现金额
            if ($amount < $configSet['min_amount']) {
                CommonUtil::throwException(ErrorConst::WITHDRAW_MIN_MONEY_LIMIT_ERROR, ErrorConst::WITHDRAW_MIN_MONEY_LIMIT_ERROR_MSG . $configSet['min_amount'] . '元');
            }

            //每日提现次数限制
            //$withdrawNumDayLimit = CommunityService::getInstance()->getCommunityConfig('withdraw_num_day_limit');
            $where = [
                ['user_id', '=', $this->userinfo->id],
                ['status', 'in', [0, 1]],
                ['create_at', '>', date('Y-m-d')],
            ];
            $withdrawCount = MemberWithdraw::getInstance()->where($where)->count();
            if ($withdrawCount >= $configSet['times']) {
                CommonUtil::throwException(ErrorConst::WITHDRAW_NUM_DAY_LIMIT_ERROR, ErrorConst::WITHDRAW_NUM_DAY_LIMIT_ERROR_MSG . $configSet['times'] . '次');
            }

            if($type == 2){
                if($configSet['toalipay'] != 1){
                    CommonUtil::throwException(ErrorConst::PARAM_ERROR, '支付宝渠道未开户');
                }
            }
            if($type == 3){
                if($configSet['topurse'] != 1){
                    CommonUtil::throwException(ErrorConst::PARAM_ERROR, '电子钱包渠道未开户');
                }
            }
            $withdrawSecondToMoney = $configSet['audit_amount'];

            //可提现金额
            if($configSet['can_amount'] > 0 && $finance['amount'] < $configSet['can_amount']){
                CommonUtil::throwException(ErrorConst::PARAM_ERROR,'可提现余额不足:'.$configSet['can_amount'].'元');
            }
        }


        //提现秒到少于
        if ($amount <= $withdrawSecondToMoney) {
            MemberWithdraw::getInstance()->startTrans();
            $orderNo = CommunityService::getInstance()->withdraw($this->userinfo->id, $amount, $account['aliName'], $account['aliAccount'], $type, $finance);
            if (!$orderNo) {
                MemberWithdraw::getInstance()->rollback();
                CommonUtil::throwException(ErrorConst::WITHDRAW_ERROR, ErrorConst::WITHDRAW_ERROR_MSG);
            }
            //自动到账
            $data = [];
            if ($type == 2) { //支付宝
                $data = AlipayService::getInstance()->transfer($orderNo, $amount, $account['aliName'], $account['aliAccount']);
            } elseif ($type == 3) { //杉德
                $data = SandService::getInstance()->transfer($amount, env('SAND.consumeMid'), SandConst::PREFIX . $this->userinfo->id, 0, $orderNo);
            }

            if (empty($data)) {
                MemberWithdraw::getInstance()->rollback();
                CommonUtil::throwException(ErrorConst::WITHDRAW_ERROR, ErrorConst::WITHDRAW_ERROR_MSG);
            }
            if ($data['code'] != 1) {
                MemberWithdraw::getInstance()->rollback();
                Log::error($this->userinfo->id.'提现失败：'.json_encode($data, 256));
                //CommonUtil::throwException(ErrorConst::WITHDRAW_ERROR, $data['data']);
                CommonUtil::throwException(ErrorConst::WITHDRAW_ERROR, '提现渠道维护中，请稍后再试');
            }
            $withdrawData = [
                'status' => 1,
                'audit_at' => date('Y-m-d H:i:s'),
            ];
            $ret = MemberWithdraw::getInstance()->where('order_no', $orderNo)->update($withdrawData);
            if (!$ret) {
                MemberWithdraw::getInstance()->rollback();
                CommonUtil::throwException(ErrorConst::WITHDRAW_ERROR, ErrorConst::WITHDRAW_ERROR_MSG);
            }
            MemberWithdraw::getInstance()->commit();
        } else {
            $return = CommunityService::getInstance()->withdraw($this->userinfo->id, $amount, $account['aliName'], $account['aliAccount'], $type, $finance);
            if (!$return) {
                CommonUtil::throwException(ErrorConst::WITHDRAW_ERROR, ErrorConst::WITHDRAW_ERROR_MSG);
            }
        }

        return true;
    }

    /**
     * 我的钱包
     * @param $startAt
     * @param $endAt
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function myAmountInfo(): array
    {
        $userId = $this->userinfo->id;
        $userCommunityInfo = MemberService::getInstance()->finance($userId);
        $userInfo = MemberService::getInstance()->getUserInfo($userId);
        $data = SandLogic::getInstance()->accountBalanceQuery($userId);
        return [
            'isCareer' => empty($userBusiness) ? 0 : 1,
            'isPartner' => $userInfo['isPartner'],
            'communityAmount' => $userCommunityInfo['communityAmount'],
            //'allCommunityAmount'   => $userCommunityInfo['allCommunityAmount'],
            'communityEarnings' => $userCommunityInfo['communityEarnings'], //社区收益
            'businessEarnings' => $userCommunityInfo['communityShopEarnings'], //商家收益
            'serviceEarnings' => $userCommunityInfo['communityServiceEarnings'], //服务商收益
            'areaEarnings' => $userCommunityInfo['communityAreaEarnings'], //区域收益
            'areaUserEarnings' => $userCommunityInfo['communityAreaUserEarnings'], //区域用户收益
            'amount' => $userCommunityInfo['amount'],
            'sandAmount' => $data['accountList'][0]['availableBal'] ?? 0.00,
        ];
    }

    public function waitPayList($type, $page, $pageSize): array
    {
        return ['rows' => []];
    }

    /**
     * 社区列表
     * @param $type
     * @param $page
     * @param $pageSize
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function communityList($type, $page, $pageSize): array
    {
        $list = CommunityService::getInstance()->getCommunityList($type, $page, $pageSize);

        if ($page == 1) {
            $userId = $this->userinfo->id;
            //获取我的余额和入住社区数
            $userCommunityInfo = MemberService::getInstance()->finance($userId);
            $myCommunityCount = CommunityUser::getInstance()->where(['user_id' => $userId])->count();
        }
        return ['rows' => $list, 'communityAmount' => $userCommunityInfo['communityAmount'] ?? 0, 'myCommunityCount' => $myCommunityCount ?? 0];
    }

    /**
     * @param $communityId
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    protected function getCommunityNextInfo($communityId): array
    {
        //$communityInfo = CommunityService::getInstance()->getCommunityUser($communityId);
        $communityInfo = RedisCache::hGetAll(KeysUtil::getCommunityInfo($communityId));
        if (empty($communityInfo)) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }

        if (!in_array($communityInfo['community_status'], [CommunityConst::CAN_STATUS, CommunityConst::RELEASE_STATUS, CommunityConst::BUY_STATUS])) {
            CommonUtil::throwException(ErrorConst::COMMUNITY_IN_PAY_ERROR, ErrorConst::COMMUNITY_IN_PAY_ERROR_MSG);
        }
        //获得上次社区订单
        $lastCommunityOrder = CommunityService::getInstance()->getLastCommunityOrder($communityInfo['last_order_id']);
        //计算下一次社区价格
        $rateInfo = CommunityService::getInstance()->getCommunityPrice($communityInfo['total_amount'], $lastCommunityOrder);
        $communityInfo['price'] = $rateInfo['price'];
        $communityInfo['rateWeek'] = $rateInfo['rateWeek'];
        $communityInfo['settlementRate'] = $rateInfo['settlementRate'];
        $communityInfo['lastPrice'] = $communityInfo['last_enter_amount'];
        $communityInfo['totalAmount'] = $rateInfo['totalAmount'];
        $communityInfo['premium'] = $rateInfo['premium'];
        return $communityInfo;
    }

    /**
     * 社区类型列表
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function getCateList(): array
    {
        $list = CommunityService::getInstance()->getCateList();
        return ['rows' => $list];
    }

    /**
     * 转让订单生成
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function createCommunityOp($rate, $image, $orderId, $signImage): array
    {
        if (!RedLock::getInstance()->lock('communityOp:' . $this->userinfo->id, 1)) {
            CommonUtil::throwException(ErrorConst::FREQUENT_ERROR, ErrorConst::FREQUENT_ERROR_MSG);
        }

        if (empty($rate) || empty($orderId)) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }

        $isUserTransfer = CommunityService::getInstance()->getCommunityConfig('is_user_transfer');
        if($isUserTransfer == 0){
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, '转让已关闭');
        }

        $settlementRate = CommunityService::getInstance()->getCommunityConfig('settlement_rate');
        list($start, $end) = explode('~', $settlementRate);
        $improve = CommunityService::getInstance()->improveRate($this->userinfo->id, $orderId);
        $end = $end + $improve[1];
        if ($rate < $start || $rate > $end) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }

        $where = [
            ['id', '=', $orderId],
        ];
        $communityOrder = CommunityOrder::getInstance()->where($where)->find();
        if (empty($communityOrder)) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }

        $communityUser = CommunityUser::getInstance()->where('community_id', $communityOrder['community_id'])->find();
        if (empty($communityUser)) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }
        $buyStatus = Member::getInstance()->where('id',$this->userinfo->id)->value('buy_status');
        $transferGt = CommunityService::getInstance()->getCommunityConfig('transfer_gt');
        if($buyStatus == 0 && $transferGt > 0){
            //入驻金额<1500，转让社区本金<1500
            //入驻金额>=1500，转让社区本金>=1500
            if($communityUser['lastEnterAmount'] > $transferGt){
                $where = [
                    ['user_id','=',$this->userinfo->id],
                    ['last_enter_time','>=',date('Y-m-d')],
                ];
                $money = CommunityUser::getInstance()->where($where)->order('last_enter_amount desc')->value('last_enter_amount');
                if($money <= $transferGt){
                    CommonUtil::throwException(ErrorConst::PARAM_ERROR, '入驻金额不足');
                }
            }
        }

        //不是考核中状态
        if ($communityUser['communityStatus'] != CommunityConst::CHECK_STATUS) {
            CommonUtil::throwException(ErrorConst::STATUS_ERROR, ErrorConst::STATUS_ERROR_MSG);
        }

        $checkingDays = CommunityService::getInstance()->getCommunityConfig('checking_days');
        $expireAt = strtotime('+' . $checkingDays . ' days', strtotime($communityUser['opTime']));
        //未到转让时间
        if (time() < $expireAt) {
            CommonUtil::throwException(ErrorConst::TRANSFER_NOT_TIME_ERROR, ErrorConst::TRANSFER_NOT_TIME_ERROR_MSG);
        }

        $where = [
            ['user_id','=',$this->userinfo->id],
            ['community_id','=',$communityOrder['community_id']],
            ['create_at','>=',date('Y-m-d')],
        ];
        $exist = CommunityOpOrder::getInstance()->where($where)->count();
        if($exist > 0){
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, '不能重复转让，请刷新页面');
        }
        $transferConfig = CommunityService::getInstance()->getCommunityConfig('transfer_config');
        if($buyStatus == 0 && isset($transferConfig['status']) && $transferConfig['status'] == 1){
            $where = [
                ['user_id','=',$this->userinfo->id],
                ['create_at','>=',date('Y-m-d')],
            ];
            $count = CommunityOpOrder::getInstance()->where($where)->count();
            $everyCount = CommunityService::getInstance()->everyTransferCount($this->userinfo->id);
            if($count >= $everyCount){
                CommonUtil::throwException(ErrorConst::PARAM_ERROR, '暂无转让次数');
            }
        }

        $memberNum = MemberInfoService::getInstance()->memberNum($this->userinfo->id);
        if($buyStatus == 0 && isset($transferConfig['limit_status']) && $transferConfig['limit_status'] == 1){
            $now = date('Y-m-d H:i:s');
            if($now >= $transferConfig['start_time'] && $now <= $transferConfig['end_time']){
                $where = [
                    ['user_id','=',$this->userinfo->id],
                    ['status','=',1]
                ];
                $lock = CommunityLockLog::getInstance()->where('user_id',$this->userinfo->id)->order('id desc')->find();
                if(!empty($lock)){
                    $where[] = ['create_at','>=',$lock['createAt']];
                }
                $userTotal = MemberCommunityAmountLog::getInstance()->where($where)->sum('amount') ?: 0;
                $max = CommunityService::getInstance()->transferMaxMoney($this->userinfo->id);
                if($userTotal >= $max){
                    CommonUtil::throwException(ErrorConst::PARAM_ERROR, '您的收益达到上限，需锁定一个考核中社区');
                }
                if(empty($memberNum) || $memberNum['transferCount'] < 1){
                    CommonUtil::throwException(ErrorConst::PARAM_ERROR, '您还没有入驻社区');
                }
            }
        }
        //转售价格
        $settlementPrice = CommunityService::getInstance()->getCommunityConfig('settlement_price');
        $transferRate = CommunityService::getInstance()->getCommunityConfig('transfer_rate');

        $price = $communityOrder['totalAmount'] > 0 ? $communityOrder['totalAmount'] : $settlementPrice;
        $payPrice = round($price * $rate * 0.01 * $transferRate * 0.01, 2);
        $data = [
            'community_id' => $communityOrder['community_id'],
            'order_id' => $orderId,
            'pay_price' => $payPrice,
            'rate' => $rate,
            'community_price' => $communityOrder['totalAmount'],
            'service_rate' => $transferRate,
            'user_id' => $this->userinfo->id,
            'image' => $image,
            'order_no' => getNo('OP'),
            'create_at' => date('Y-m-d H:i:s'),
            'premium' => round($price * $rate * 0.01, 2),
            'sign_image' => $signImage
        ];

        CommunityOpOrder::getInstance()->startTrans();
        try {
            CommunityOpOrder::getInstance()->insert($data);
            $communityUserData = [
                'op_order_no' => $data['order_no'],
                'op_price' => $payPrice ?? 0,
                //新社区不用付钱转让
                'is_pay_service' => $communityUser['isFirst'],
                'is_sign' => 1,
                'update_at' => date('Y-m-d H:i:s'),
            ];
            CommunityUser::getInstance()->where('community_id', $communityOrder['community_id'])->update($communityUserData);

            if($buyStatus == 0 && isset($transferConfig['limit_status']) && $transferConfig['limit_status'] == 1){
                $now = date('Y-m-d H:i:s');
                if($now >= $transferConfig['start_time'] && $now <= $transferConfig['end_time']){
                    if(!empty($memberNum) && $memberNum['transferCount'] > 0){
                        MemberInfoService::getInstance()->addCommunityTransferCount($this->userinfo->id,1,2);
                    }
                }
            }

            //更新社区
            foreach ($communityUserData as $k => $v) {
                RedisCache::hSet(KeysUtil::getCommunityInfo($communityUser['communityId']), $k, $v);
            }

        } catch (\Exception $e) {
            CommunityOpOrder::getInstance()->rollback();
            CommonUtil::throwException(ErrorConst::EXCEPTION_ERROR, $e->getMessage());
        }
        CommunityOpOrder::getInstance()->commit();
        return $data;
    }

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function opStatus($orderId): bool
    {
        if (empty($orderId)) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }
        $where = [
            ['id', '=', $orderId],
            ['user_id', '=', $this->userinfo->id],
        ];
        $communityOrder = CommunityOrder::getInstance()->where($where)->find();
        if (empty($communityOrder)) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }
        $where = [
            ['community_id', '=', $communityOrder['community_id']],
            ['user_id', '=', $this->userinfo->id],
        ];
        $data = [
            'op_time' => date('Y-m-d H:i:s'),
            'community_status' => 6,
        ];
        $res = CommunityUser::getInstance()->where($where)->update($data);
        if (!$res) {
            return false;
        }
        return true;
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function payOpOrder($orderNo, $type, $payPassword, $paySubType, $image, $signImage, $orderId): array
    {
        if (!RedLock::getInstance()->lock('payOpOrder:' . $orderNo, 1)) {
            CommonUtil::throwException(ErrorConst::FREQUENT_ERROR, ErrorConst::FREQUENT_ERROR_MSG);
        }

        if (!in_array($type, [1, 2, 3, 4])) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }

        //验证支付密码
        if ($type == 3) {
            $account = MemberService::getInstance()->account($this->userinfo->id);
            if (empty($account)) {
                CommonUtil::throwException(ErrorConst::NO_PAY_PASSWORD_ERROR, ErrorConst::NO_PAY_PASSWORD_ERROR_MSG);
            }
            if ($account['payPwd'] != $payPassword) {
                CommonUtil::throwException(ErrorConst::PAY_PASSWORD_ERROR, ErrorConst::PAY_PASSWORD_ERROR_MSG);
            }
        }

        //获取订单
        $orderInfo = CommunityOpOrder::getInstance()->where('order_no', $orderNo)->find();

        //订单不存在 订单状态错误      订单用户id错误 ，订单时间超时
        if (empty($orderInfo) || $orderInfo['is_pay'] != 0) {
            CommonUtil::throwException(ErrorConst::NO_ORDER_ERROR, ErrorConst::NO_ORDER_ERROR_MSG);
        }

        if($orderInfo['userId'] == $this->userinfo->id){
            CommonUtil::throwException(ErrorConst::NO_ORDER_ERROR, '重复支付订单，请刷新页面');
        }

        //更新支付用户
        $orderInfo->pay_user_id = $this->userinfo->id;
        $orderInfo->image = $image;
        $orderInfo->sign_image = $signImage;
        $orderInfo->save();

        //更新签名
        if ($orderId) {
            //待经营签名
            CommunityOrder::getInstance()->where('id', $orderId)->update(['image' => $image, 'sign_image' => $signImage]);
        }

        $amountPrice = 0;
        $signPrice = 0;
        //获取余额
        if ($type == 3) {
            $userBalance = MemberService::getInstance()->finance($this->userinfo->id);
            $amountPrice = $userBalance['amount'];
        }

        $payPrice = $orderInfo['pay_price'];
        $isBalance = 0;
        if ($type == 3 && $amountPrice < $payPrice) {
            CommonUtil::throwException(ErrorConst::NO_PRICE_ERROR, ErrorConst::NO_PRICE_ERROR_MSG);
        }
        if ($type == 3) {
            //社区余额
            $amountPrice = $payPrice;
            $thirdPayPrice = 0;
            $isBalance = 1;
        } else {
            $thirdPayPrice = $payPrice;
        }

        if (!RedLock::getInstance()->lock('createOpOrderPay:' . $orderNo, 60)) {
            CommonUtil::throwException(ErrorConst::FREQUENT_ERROR, ErrorConst::OP_PAY_LIMIT_ERROR_MSG);
        }

        $payInfo = CommunityService::getInstance()->payOpOrder($orderInfo, $thirdPayPrice, $amountPrice, $signPrice, $type);
        if (!$payInfo) {
            CommonUtil::throwException(ErrorConst::SYSTEM_ERROR, ErrorConst::SYSTEM_ERROR_MSG);
        }

        //有微信支付
        $userInfo = MemberService::getInstance()->getUserInfo($this->userinfo->id);
        $pay = [];
        if ($isBalance) {
            //余额全付
            /*$info = [
                'pay_status' => 3,
                'pay_no' => $payInfo['pay_no'],
                'money' => $payInfo['community_pay_amount'],
                'trade_no' => '',
                'receipt_data' => '',
            ];
            $info = PayService::getInstance()->payFormOrder($info);
            if (!$info) {
                CommonUtil::throwException(ErrorConst::SYSTEM_ERROR, ErrorConst::SYSTEM_ERROR_MSG);
            }*/
            $info = [
                'pay_status' => 3,
                'pay_no' => $payInfo['pay_no'],
                'money' => $payInfo['community_pay_amount'],
                'trade_no' => '',
                'receipt_data' => '',
            ];
            $event["exchange"] = config('rabbitmq.order_callback_queue');
            RabbitMqService::send($event, $info);
        } elseif ($type == 4) {
            if (env('test.is_test') == 1) {
                $thirdPayPrice = 0.01;
            }
            $pay = SandLogic::getInstance()->orderCreate($userInfo['userId'], $thirdPayPrice, $payInfo['pay_no']);
        } else {
            $pay = PayService::getInstance()->toPay($payInfo, $userInfo, $type, $paySubType);
        }

        return ['payInfo' => $pay, 'isBalance' => $isBalance];
    }

    /**
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws DataNotFoundException
     */
    public function getLastCommunityOrder($orderId): array
    {
        $info = CommunityService::getInstance()->getLastCommunityOrder($orderId);
        if (empty($info)) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }
        $settlementRate = CommunityService::getInstance()->getCommunityConfig('settlement_rate');
        $transferRate = CommunityService::getInstance()->getCommunityConfig('transfer_rate');
        $arr = explode('~', $settlementRate);
        $info['startRate'] = $arr[0];
        $info['endRate'] = $arr[1];
        $info['transferRate'] = $transferRate;
        $info['account'] = MemberAccountCache::getKeyData($info['userId']);
        return $info;
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function getCommunityOrder($orderId): array
    {
        $info = CommunityOrder::getInstance()->where('id', $orderId)->find()->toArray();
        if (empty($info)) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }
        $settlementRate = CommunityService::getInstance()->getCommunityConfig('settlement_rate');
        $transferRate = CommunityService::getInstance()->getCommunityConfig('transfer_rate');

        //提升转让比例
        $improve = CommunityService::getInstance()->improveRate($this->userinfo->id, $orderId);

        //转让服务费比例
        //$userCommunityRate = CommunityService::getInstance()->getCommunityConfig('member_settlement_rate');
        //$transferRate = 100 - ($userCommunityRate + $improve[0]);

        $arr = explode('~', $settlementRate);
        $info['startRate'] = $arr[0];
        $info['endRate'] = $arr[1] + $improve[1];
        //转让服务费比例
        $info['transferRate'] = $transferRate;
        return $info;
    }


    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function communityTask($communityId, $orderId): array
    {
        if (empty($communityId)) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }
        $communityUser = CommunityService::getInstance()->getCommunityUser($communityId);
        if (empty($communityUser)) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }
        if(empty($orderId)){
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, '社区订单ID不能为空');
        }
        $end = strtotime(date('Y-m-d 23:59:59'));
        $expire = $end - time();
        RedisCache::set(KeysUtil::getCommunityTaskKey($this->userinfo->id), $orderId, $expire);

        $data = CommunityService::getInstance()->getCommunityConfig('checking_criterion');
        if (empty($data) || empty($data['data']) || $data['status'] == 0) {
            return ['rows' => [], 'info' => []];
        }

        //推荐会员
        //$userCount = Member::getInstance()->where('invite_id', $this->userinfo->id)->count();
        $where = [
            ['create_at','>=',date('Y-m-d')],
            ['invite_id','=',$this->userinfo->id],
            ['community_order_id','=',$orderId]
        ];
        $userTaskMoney = 0;
        $shopTaskMoney = 0;
        foreach ($data['data'] as &$v) {
            if($v['task_type'] == 1 && $v['task_money'] > 0){
                $userTaskMoney = $v['task_money'];
            }
            if($v['task_type'] == 2 && $v['task_money'] > 0){
                $shopTaskMoney = $v['task_money'];
            }
        }
        $userCount = Member::getInstance()->where($where)->count();
        if($userCount > 0 && $userTaskMoney > 0){
            $userCount = 0;
            $userIds = Member::getInstance()->where($where)->column('id');
            foreach($userIds as $uid){
                $where = [
                    ['user_id', '=', $uid],
                    ['status', '=', 1],
                    ['order_status', 'in', [0,5,6]],
                    ['create_at','>=',date('Y-m-d')]
                ];
                $payPrice = OrderPay::getInstance()->where($where)->sum('pay_price') ?: 0;
                if($payPrice >= $userTaskMoney){
                    $userCount+=1;
                }
            }
        }


        //推荐商家
        /*$where = [
            ['invite_id', '=', $this->userinfo->id],
            ['is_shop', '=', 1],
        ];*/
        //$shopCount = Member::getInstance()->where($where)->count();
        $shopCount = 0;
        $where = [
            ['invite_id', '=', $this->userinfo->id],
            ['is_shop', '=', 1],
            ['community_order_id','=',$orderId],
            ['create_at','>=',date('Y-m-d')]
        ];
        $ids = Member::getInstance()->where($where)->column('id');
        if(!empty($ids)){
            $where = [
                ['user_id','in',$ids],
                ['status','=',1],
                ['auth_at','>=',date('Y-m-d')],
                ['create_at','>=',date('Y-m-d')]
            ];
            $shopIds = Shop::getInstance()->where($where)->column('id');
            $shopCount = !empty($shopIds) ? count($shopIds) : 0;
            if($shopCount > 0 && $shopTaskMoney > 0){
                $shopCount = 0;
                foreach($shopIds as $shopId){
                    //1待发货 2待收款 3已收货 4已完成
                    $where = [
                        ['shop_id','=',$shopId],
                        ['status','in',[1,2,3,4]],
                        ['create_at','>=',date('Y-m-d')]
                    ];
                    $payPrice = OrderShop::getInstance()->where($where)->sum('pay_price') ?: 0;
                    if($payPrice >= $shopTaskMoney){
                        $shopCount+=1;
                    }
                }

            }
        }


        //平台消费
        $where = [
            ['user_id', '=', $this->userinfo->id],
            ['status', '=', 1],
            ['order_status', 'in', [0, 5, 6]],
            ['community_order_id','=',$orderId]
        ];
        foreach ($data['data'] as &$v) {
            if($v['task_type'] == 3 && $v['task_money'] > 0){
                $where[] = ['pay_price','>=',$v['task_money']];
            }
        }
        $orderCount = OrderPay::getInstance()->where($where)->count();

        //看广告
        /*$where = [
            ['user_id', '=', $this->userinfo->id],
            ['status', '=', 1],
            ['log_type', '=', 'adv']
        ];
        $advCount = MemberGxzLog::getInstance()->where($where)->count();*/
        $dataArr = [];
        foreach ($data['data'] as &$v) {
            $status = 0;
            $v['num'] = $v['task_num'];
            $v['complete_num'] = 0;
            $v['rate'] = $v['award_num'];
            switch ($v['task_type']) {
                case 1:
                    //推荐会员
                    $v['complete_num'] = $userCount;
                    if ($userCount >= $v['task_num']) {
                        $status = 1;
                    }

                    $v['name'] = '推荐（' . $v['task_num'] . '）个会员';
                    break;
                case 2:
                    //推荐商家
                    $v['complete_num'] = $shopCount;
                    if ($shopCount >= $v['task_num'] && $shopTaskMoney >= $v['task_money']) {
                        $status = 1;
                    }
                    $v['name'] = '推荐（' . $v['task_num'] . '）个商家';
                    break;
                case 3:
                    //平台消费
                    $v['complete_num'] = $orderCount;
                    if ($orderCount >= $v['task_num']) {
                        $status = 1;
                    }
                    $v['name'] = '经营过程中平台消费（' . $v['task_num'] . '）次以上';
                    break;
                case 4:
                    //看广告
                    $where = [
                        ['user_id', '=', $this->userinfo->id],
                        ['log_type', '=', 'adv'],
                        ['order_id', '=', $orderId],
                    ];
                    $advCount = CommunityTaskLog::getInstance()->where($where)->count();
                    $v['complete_num'] = $advCount;
                    if ($advCount >= $v['task_num']) {
                        $status = 1;
                    }
                    $v['name'] = '观看广告（' . $v['task_num'] . '）次以上';
                    break;
            }
            $task = CommunityService::getInstance()->tasksLog($v['complete_num'],$orderId,$this->userinfo->id,$v['task_type'],$status);
            $v['complete_num'] = $task['completeNum'] ?? 0;
            $v['status'] = $task['status'] ?? 0;
            $dataArr[] = $v;
        }

        return ['rows' => $dataArr, 'info' => $communityUser];
    }

    /**
     * @param array $communityInfo
     * @param array $data
     * @return array
     */
    public function getArr(array $communityInfo, array $data): array
    {
        //$userName = !empty($communityInfo['user_id']) ? RedisCache::hGet(KeysUtil::getMemberInfoKey($communityInfo['user_id']), 'user_name') : '平台';
        $data[] = [
            'userName' => $this->getCommunityUserName($communityInfo),
            'address' => $communityInfo['address'],
            'communityName' => $communityInfo['community_name'],
            'communityId' => $communityInfo['community_id'],
            'lastEnterAmount' => $communityInfo['last_enter_amount'],
            'shopAmount' => $communityInfo['shop_amount'],
            'shopNum' => $communityInfo['shop_num'],
            'lastEnterTime' => $communityInfo['last_enter_time'],
            'userCount' => $communityInfo['user_count'],
            'userAmount' => $communityInfo['user_amount'],
            'type' => $communityInfo['type']
        ];
        return $data;
    }

    public function getCommunityUserName($communityInfo)
    {
        $userName = '平台';
        if (!empty($communityInfo['user_id'])) {
            $userName = RedisCache::hGet(KeysUtil::getMemberInfoKey($communityInfo['user_id']), 'user_name');
            if (!$userName) {
                $member = Member::getInstance()->where('id', $communityInfo['user_id'])->find();
                if ($member) {
                    $memberArr = CommonUtil::camelToUnderLine($member->toArray());
                    RedisCache::hMSet(KeysUtil::getMemberInfoKey($communityInfo['user_id']), $memberArr);
                    $userName = $member['user_name'];
                } else {
                    $userName = '';
                }
            }
        }
        return $userName;
    }

    /**
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws DataNotFoundException
     * @throws \Exception
     */
    public function report($startAt, $endAt): array
    {
        $member = Member::getInstance()->where('id', $this->userinfo->id)->find();
        $where = [];
        switch ($member['is_agency']) {
            case 1:
                $where[] = ['province_id', '=', $member['province_id']];
                break;
            case 2:
                $where[] = ['city_id', '=', $member['city_id']];
                break;
            case 3:
                if ($member['country_id']) {
                    $where[] = ['country_id', '=', $member['country_id']];
                } else {
                    $where[] = ['street_id', '=', $member['street_id']];
                }
                break;
        }
        $where[] = ['create_at', 'between', [$startAt, $endAt . " 23:59:59"]];
        //注册会员
        $memberCount = Member::getInstance()->where($where)->count();
        //入驻商家
        $shopCount = Member::getInstance()->where($where)->where('is_shop', 1)->count();
        //余额
        $amount = Finance::getInstance()->where('user_id', $this->userinfo->id)->value('amount');
        //社区收益
        $fieldData = [
            'COALESCE(sum(if(status = 1 and type = 0,amount,0))) as community_income',
            'COALESCE(sum(if(status = 1 and type = 1,amount,0))) as packs_income',
            'COALESCE(sum(if(status = 1 and type = 2,amount,0))) as invite_income',
            'COALESCE(sum(if(status = 1 and type = 3,amount,0))) as bonus_income',
        ];
        $log = MemberCommunityAmountLog::getInstance()
            ->field($fieldData)
            ->where('user_id', $this->userinfo->id)
            ->where([['create_at', 'between', [$startAt, $endAt . " 23:59:59"]]])
            ->find();

        $list = [];
        if ($startAt == $endAt) {
            //一天显示小时
            for ($i = 0; $i < 24; $i++) {
                $time = str_pad($i, 2, "0", STR_PAD_LEFT);;
                $start = "$startAt $time:00:00";
                $end = "$startAt $time:59:59";
                $data = $this->getDayList($start, $end, 1);
                $list['date'][] = $data['date'];
                $list['income'][] = $data['income'];
                $list['expend'][] = $data['expend'];
            }
        } else {
            //天数
            $date1 = new DateTime(date('Y-m-d H:i:s', strtotime($startAt)));
            $date2 = new DateTime(date('Y-m-d 23:59:59', strtotime($endAt)));
            $days = $date2->diff($date1)->days + 1;
            $start = strtotime($startAt);
            for ($i = 1; $i <= $days; $i++) {
                $end = strtotime("+$i day", strtotime($startAt)) - 1;
                $startFormat = date('Y-m-d H:i:s', $start);
                $endFormat = date('Y-m-d H:i:s', $end);
                $start = $end + 1;
                $data = $this->getDayList($startFormat, $endFormat, 2);
                $list['date'][] = $data['date'];
                $list['income'][] = $data['income'];
                $list['expend'][] = $data['expend'];
            }
        }
        return [
            'memberCount' => $memberCount,
            'shopCount' => $shopCount,
            'amount' => $amount,
            'communityIncome' => $log['communityIncome'] ?? "0.00",
            'packsIncome' => $log['packsIncome'] ?? "0.00",
            'inviteIncome' => $log['inviteIncome'] ?? "0.00",
            'bonusIncome' => $log['bonusIncome'] ?? "0.00",
            'list' => $list,
        ];
    }

    /**
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws DataNotFoundException
     */
    public function getDayList($start, $end, $type): array
    {

        $fieldData = [
            'COALESCE(sum(if(status = 1,amount,0))) as income',
            'COALESCE(sum(if(status = 2,amount,0))) as expend',
        ];
        $dayData = MemberCommunityAmountLog::getInstance()
            ->field($fieldData)
            ->where('user_id', $this->userinfo->id)
            ->where([['create_at', 'between', [$start, $end]]])
            ->find();
        if ($type == 1) {
            //一天
            $start = date('H', strtotime($start));
        } else {
            //跨天
            $start = date('m-d', strtotime($start));
        }
        return [
            'date' => $start,
            'income' => $dayData['income'] ?? "0.00",
            'expend' => $dayData['expend'] ?? "0.00"
        ];
    }

    public function communityTaskForAdv($communityId, $orderId): bool
    {
        if (!RedLock::getInstance()->lock('communityTaskForAdv:' . $this->userinfo->id . ':' . request()->ip(), 1)) {
            CommonUtil::throwException(ErrorConst::FREQUENT_ERROR, ErrorConst::FREQUENT_ERROR_MSG);
        }
        $event["exchange"] = config('rabbitmq.info_queue');
        $data = ['type' => 'task_for_adv', 'data' => ['userId' => $this->userinfo->id, 'communityId' => $communityId, 'orderId' => $orderId]];
        RabbitMqService::send($event, $data);
        return true;
    }

    /**
     * 立即锁定
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function communityLock($communityId): bool
    {
        if (empty($communityId)) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }
        $communityUser = CommunityService::getInstance()->getCommunityUser($communityId);
        if (empty($communityUser)) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }
        if ($communityUser['communityStatus'] != CommunityConst::CHECK_STATUS) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }
        $config = CommunityService::getInstance()->getCommunityConfig('buy_community_config');
        if (!isset($config['lock_status']) || $config['lock_status'] != 1) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }

        CommunityUser::getInstance()->startTrans();
        try {
            $time = date('Y-m-d H:i:s');
            $data = [
                'community_status' => CommunityConst::PERMANENT_STATUS,
                'update_at' => $time,
                'permanent_time' => $time,
                'last_enter_time' => $time
            ];
            CommunityUser::getInstance()->where('community_id', $communityId)->update($data);

            $lockData = [
                'user_id' => $this->userinfo->id,
                'community_id' => $communityId,
                'community_name' => $communityUser['communityName'],
                'order_id' => $communityUser['lastOrderId'],
            ];
            CommunityLockLog::getInstance()->insert($lockData);

            if (isset($config['lock_award_status']) && $config['lock_award_status'] == 1) {
                if ($config['lock_award_gxz'] > 0) {
                    //赠送贡献值
                    $msg = '社区锁定，赠送贡献值';
                    $gxz = bcmul($communityUser['totalAmount'], $config['lock_award_gxz'] * 0.01, 2);
                    MemberService::getInstance()->addFinanceLog($this->userinfo->id, 'community_lock', $gxz, 7, $msg, '');
                }
                if (isset($config['lock_award_coupon_status']) && $config['lock_award_coupon_status'] == 1) {
                    if (!empty($config['lock_award_coupon_ids'])) {
                        CouponService::getInstance()->sendCouponByIds($this->userinfo->id, $config['lock_award_coupon_ids']);
                    }
                }
            }
        } catch (\Exception $e) {
            Log::error($e->getMessage());
            CommunityUser::getInstance()->rollback();
            return false;
        }
        CommunityUser::getInstance()->commit();
        return true;
    }

    /**
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws DataNotFoundException
     */
    public function communityExchangeList($page, $pageSize, $name, $provinceId, $cityId, $countryId, $streetId, $commId, $communityId): array
    {
        $where = [
            //1锁定 2解锁
            ['c.lock_status', '=', 1]
        ];
        if (!empty($name)) {
            $where[] = ['c.name', 'like', "%$name%"];
        }
        if (!empty($provinceId)) {
            $where[] = ['c.province_id', '=', $provinceId];
        }
        if (!empty($cityId)) {
            $where[] = ['c.city_id', '=', $cityId];
        }
        if (!empty($countryId)) {
            $where[] = ['c.country_id', '=', $countryId];
        }
        if (!empty($streetId)) {
            $where[] = ['c.street_id', '=', $streetId];
        }
        if (!empty($commId)) {
            $where[] = ['c.comm_id', '=', $commId];
        }
        $field = 'c.id community_id,c.name community_name,c.province_id,c.city_id,country_id,c.lock_status,c.province,c.city,c.country,c.street,u.total_amount,op_price';
        $list = Community::getInstance()->alias('c')
            ->leftJoin('community_user u', 'c.id=u.community_id')
            ->where($where)
            ->field($field)
            ->page($page, $pageSize)
            ->select();
        foreach ($list as &$v) {
            $communityInfo = RedisCache::hGetAll(KeysUtil::getCommunityInfo($v['community_id']));
            $v['userName'] = $this->getCommunityUserName($communityInfo);
            $v['address'] = $v['province'] . $v['city'] . $v['country'] . $v['street'];
            $v['userId'] = !empty($communityInfo['user_id']) ? $communityInfo['user_id'] : 0;
        }
        $info = CommunityUser::getInstance()->where('community_id', $communityId)->field('community_id,community_name,address')->find();
        return ['list' => $list, 'info' => $info];
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function communityExchange($oriCommunityId, $exCommunityId): bool
    {
        if (!RedLock::getInstance()->lock('communityExchange:' . $this->userinfo->id, 1)) {
            CommonUtil::throwException(ErrorConst::FREQUENT_ERROR, ErrorConst::FREQUENT_ERROR_MSG);
        }
        if (empty($oriCommunityId) || empty($exCommunityId)) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }

        $config = CommunityService::getInstance()->getCommunityConfig('buy_community_config');
        if ($config['exchange_status'] != 1) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, '未开启兑换');
        }

        $where = [
            'user_id' => $this->userinfo->id,
            'ex_community_id' => $oriCommunityId
        ];
        $count = CommunityExchangeLog::getInstance()->where($where)->order('id desc')->value('num') ?: 0;
        if ($count >= $config['exchange_count']) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, '已超过兑换次数');
        }

        $where = [
            ['community_id', '=', $oriCommunityId],
            ['user_id', '=', $this->userinfo->id],
        ];
        $communityUser = CommunityUser::getInstance()->where($where)->find();
        if (empty($communityUser)) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }

        //不是经营中状态
        if ($communityUser['communityStatus'] != CommunityConst::PERMANENT_STATUS) {
            CommonUtil::throwException(ErrorConst::STATUS_ERROR, ErrorConst::STATUS_ERROR_MSG);
        }

        $where = [
            ['community_id', '=', $exCommunityId],
        ];
        $exCommunityUser = CommunityUser::getInstance()->where($where)->find();
        if (empty($exCommunityUser)) {
            $ret = CommunityService::getInstance()->createCommunityUser($exCommunityId, 0, $communityUser['totalAmount']);
            if (!$ret) {
                CommonUtil::throwException(ErrorConst::STATUS_ERROR, '复制社区失败');
            }
            $exCommunityUser = CommunityUser::getInstance()->where($where)->find();
        }

        if ($exCommunityUser['userId'] != 0) {
            CommonUtil::throwException(ErrorConst::STATUS_ERROR, '该社区已有归属人');
        }

        CommunityUser::getInstance()->startTrans();
        try {
            $where = [
                ['community_id', '=', $oriCommunityId],
            ];
            $time = date('Y-m-d H:i:s');
            $data = [
                'user_id' => 0,
                'last_enter_amount' => 0,
                'total_amount' => 0,
                'community_status' => 0,
                'update_at' => $time,
            ];
            CommunityUser::getInstance()->where($where)->update($data);

            $where = [
                ['community_id', '=', $exCommunityId],
            ];
            $data = [
                'user_id' => $this->userinfo->id,
                'last_enter_amount' => $communityUser['lastEnterAmount'],
                'total_amount' => $communityUser['totalAmount'],
                'update_at' => $time,
                'permanent_time' => $time,
                'community_status' => CommunityConst::PERMANENT_STATUS,
                'last_enter_time' => $time,
                'last_order_id' => $communityUser['lastOrderId'],
                'type' => $communityUser['type'],
            ];

            CommunityUser::getInstance()->where($where)->update($data);

            $data = [
                'community_id' => $oriCommunityId,
                'ex_community_id' => $exCommunityId,
                'user_id' => $this->userinfo->id,
                'num' => $count + 1,
            ];
            CommunityExchangeLog::getInstance()->insert($data);
        } catch (\Exception $e) {
            CommunityUser::getInstance()->rollback();
            CommonUtil::throwException(ErrorConst::EXCEPTION_ERROR, $e->getMessage());
        }
        CommunityUser::getInstance()->commit();
        return true;
    }

    /**
     * 经营中转让社区
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws DataNotFoundException
     */

    public function communityTransfer($rate, $image, $communityId, $signImage): array
    {
        if (!RedLock::getInstance()->lock('communityTransfer:' . $this->userinfo->id, 1)) {
            CommonUtil::throwException(ErrorConst::FREQUENT_ERROR, ErrorConst::FREQUENT_ERROR_MSG);
        }

        if (empty($rate) || empty($communityId)) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }

        $config = CommunityService::getInstance()->getCommunityConfig('buy_community_config');
        if ($config['transfer_status'] != 1) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, '未开启转让');
        }
        if ($rate < $config['transfer_premium_rate_start'] || $rate > $config['transfer_premium_rate_end']) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }

        $where = [
            ['community_id', '=', $communityId],
            ['user_id', '=', $this->userinfo->id],
        ];
        $communityUser = CommunityUser::getInstance()->where($where)->find();
        if (empty($communityUser)) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }

        //不是经营中状态
        if ($communityUser['communityStatus'] != CommunityConst::PERMANENT_STATUS) {
            CommonUtil::throwException(ErrorConst::STATUS_ERROR, ErrorConst::STATUS_ERROR_MSG);
        }

        //转售价格
        $premium = round($communityUser['totalAmount'] * $rate * 0.01, 2);
        $payPrice = bcadd($communityUser['totalAmount'], $premium, 2);
        $data = [
            'community_id' => $communityId,
            'order_id' => 0,
            'pay_price' => $payPrice,
            'rate' => $rate,
            'community_price' => $communityUser['totalAmount'],
            'service_rate' => $config['transfer_fee_rate'],
            'user_id' => $this->userinfo->id,
            'image' => $image,
            'order_no' => getNo('OC'),
            'premium' => $premium,
            'sign_image' => $signImage,
        ];

        CommunityOpOrder::getInstance()->startTrans();
        try {
            CommunityOpOrder::getInstance()->insert($data);
            $communityUserData = [
                'is_op_transfer' => 1,
                'op_order_no' => $data['order_no'],
                'op_price' => $payPrice ?? 0,
                'update_at' => date('Y-m-d H:i:s'),
                'lock_status' => CommunityConst::UNLOCK,
                'type' => 3,
            ];
            CommunityUser::getInstance()->where('community_id', $communityId)->update($communityUserData);
        } catch (\Exception $e) {
            CommunityOpOrder::getInstance()->rollback();
            CommonUtil::throwException(ErrorConst::EXCEPTION_ERROR, $e->getMessage());
        }
        CommunityOpOrder::getInstance()->commit();
        return $data;
    }

    /**
     * 获取锁定/购买社区配置
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function getTransferRate()
    {
        return CommunityService::getInstance()->getCommunityConfig('buy_community_config');
    }

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function hall($cateId, $name, $provinceId, $cityId, $countryId, $streetId, $page, $pageSize): array
    {
        if (!in_array($cateId, array_column($this->cateHall(), 'id'))) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }
        $config = CommunityService::getInstance()->getCommunityConfig('buy_community_config');
        if ($cateId == 3 && $config['buy_status'] != 1) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, '未开启');
        }
        if ($cateId == 3) {
            //招募广场
            $where = [
                ['u.type', '=', $cateId],
                ['u.is_op_transfer', '=', 0],
                ['u.lock_status', '=', CommunityConst::UNLOCK],
                ['u.community_status', 'in', [CommunityConst::CAN_STATUS, CommunityConst::RELEASE_STATUS]]
            ];
        } else {
            //转让大厅
            $where = [
                ['u.is_op_transfer', '=', 1],
                ['u.lock_status', '=', CommunityConst::UNLOCK]
            ];
        }
        if (!empty($name)) {
            $where[] = ['u.community_name', 'like', "%$name%"];
        }
        if (!empty($provinceId)) {
            $where[] = ['c.province_id', '=', $provinceId];
        }

        if (!empty($cityId)) {
            $where[] = ['c.city_id', '=', $cityId];
        }

        if (!empty($countryId)) {
            $where[] = ['c.country_id', '=', $countryId];
        }

        if (!empty($streetId)) {
            $where[] = ['c.street_id', '=', $streetId];
        }
        $list = CommunityUser::getInstance()->alias('u')
            ->leftJoin('community c', 'u.community_id=c.id')
            ->where($where)
            ->field('u.*')
            ->page($page, $pageSize)
            ->select();
        foreach ($list as &$v) {
            $v['userName'] = $this->getCommunityUserName($v);
            $v['payPrice'] = $config['buy_price'];
            //经营中转让
            if ($v['isOpTransfer'] == 1) {
                $opOrder = CommunityOpOrder::getInstance()->where('community_id', $v['communityId'])->order('id desc')->field('pay_price,create_at')->find();
                $v['payPrice'] = $opOrder['payPrice'];
                $v['createAt'] = $opOrder['createAt'];
            }
        }
        return !empty($list) ? $list->toArray() : [];
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function allHall($name, $provinceId, $cityId, $countryId, $streetId, $page, $pageSize): array
    {
        $config = CommunityService::getInstance()->getCommunityConfig('buy_community_config');
        $where = [];
        if (!empty($name)) {
            $where[] = ['name', 'like', "%$name%"];
        }
        if (!empty($provinceId)) {
            $where[] = ['province_id', '=', $provinceId];
        }

        if (!empty($cityId)) {
            $where[] = ['city_id', '=', $cityId];
        }

        if (!empty($countryId)) {
            $where[] = ['country_id', '=', $countryId];
        }

        if (!empty($streetId)) {
            $where[] = ['street_id', '=', $streetId];
        }
        $field = 'id community_id,name community_name,province_id,city_id,country_id,lock_status,province,city,country,street';
        $list = Community::getInstance()
            ->where($where)
            ->field($field)
            ->page($page, $pageSize)
            ->select();
        $list = !empty($list) ? $list->toArray() : [];
        $arr = [];
        foreach ($list as &$v) {
            //社区状态 0可抢购 1已释放  3被抢占 4待经营  6考核中 7被领取 8：永久社区
            //$communityInfo = RedisCache::hGetAll(KeysUtil::getCommunityInfo($v['communityId']));
            $communityInfo = CommunityUser::getInstance()->where('community_id', $v['communityId'])->find();
            if (empty($communityInfo['is_op_transfer'])) {
                if (isset($communityInfo['community_status']) && !in_array($communityInfo['community_status'], [0, 1])) {
                    unset($v);
                    continue;
                }
                //不是招募大厅类型
                if (isset($communityInfo['type']) && $communityInfo['type'] != 3) {
                    unset($v);
                    continue;
                }
            }

            $v['userName'] = $this->getCommunityUserName($communityInfo);
            //1锁定 2解锁
            $v['payPrice'] = $config['buy_price'];
            $v['cateId'] = 3;
            if (!empty($communityInfo) && $communityInfo['is_op_transfer'] == 1) {
                $v['payPrice'] = $communityInfo['opPrice'];
                $v['cateId'] = 4;
            }
            $v['address'] = $v['province'] . $v['city'] . $v['country'] . $v['street'];
            $arr[] = $v;
        }
        return !empty($arr) ? $arr : [];
    }

    /**
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws DataNotFoundException
     */
    public function cateHall(): array
    {
        $config = CommunityService::getInstance()->getCommunityConfig('buy_community_config');
        if ($config['buy_status'] == 1) {
            $data = [
                ['id' => 3, 'name' => '招募大厅'],
                ['id' => 4, 'name' => '转让大厅'],
            ];
        } else {
            $data = [
                ['id' => 4, 'name' => '转让大厅'],
            ];
        }
        return $data;
    }

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function myCommunityOpList($name, $streetId, $page, $pageSize): array
    {
        $where = [
            //['user_id','=',$this->userinfo->id],
            ['community_status', '=', 8]
        ];
        if (!empty($name)) {
            $where[] = ['u.community_name', 'like', "%$name%"];
        }
        if (!empty($streetId)) {
            $where[] = ['c.street_id', '=', $streetId];
        }
        /*$whereOr = [
            ['type','=',3],
            ['is_op_transfer','=',1],
            ['community_status','=',8]
        ];*/
        $list = CommunityUser::getInstance()->alias('u')
            ->leftJoin('community c', 'u.community_id=c.id')
            ->where($where)
            //->where(function ($query) use ($whereOr) {
            //  $query->whereOr($whereOr);
            //})
            ->field('u.*')
            ->page($page, $pageSize)
            ->select();
        foreach ($list as &$v) {
            $v['userName'] = $this->getCommunityUserName($v);
        }
        return !empty($list) ? $list->toArray() : [];
    }

    /**
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws DataNotFoundException
     */
    public function createCommunityHallOrder($communityId, $image, $signImage, $cateId): array
    {
        if (empty($communityId) || empty($image)) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }
        $communityUser = CommunityUser::getInstance()->where('community_id', $communityId)->find();
        if ($communityUser) {
            if ($communityUser['userId'] == $this->userinfo->id) {
                CommonUtil::throwException(ErrorConst::PARAM_ERROR, '不能购买自己的社区');
            }

            if($communityUser['communityStatus'] == CommunityConst::PERMANENT_STATUS){
                CommonUtil::throwException(ErrorConst::PARAM_ERROR, '社区已被抢购');
            }
        }

        $config = CommunityService::getInstance()->getCommunityConfig('buy_community_config');


        /*if($communityUser['totalAmount'] == 0){
            $premium = 0;
        }else{
            $where = [
                ['community_id', '=', $communityId]
            ];
            $communityOpOrder = CommunityOpOrder::getInstance()->where($where)->order('id desc')->find();
            //溢价
            $premium = round($communityUser['totalAmount'] * $communityOpOrder['rate'] * 0.01, 2);
        }*/

        $data = [
            'user_id' => $this->userinfo->id,
            'community_id' => $communityId,
            'last_order_id' => $communityUser['lastOrderId'] ?? 0,
            'order_no' => getNo('HA'),
            'price' => $config['buy_price'],
            'expire_at' => date('Y-m-d H:i:s', strtotime("+15 minute")),
            'total_amount' => $config['buy_price'],
            'type' => $cateId,
            'premium' => 0,
            'image' => $image,
            'sign_image' => $signImage,
        ];
        $orderId = CommunityOrder::getInstance()->insertGetId($data);
        return ['orderInfo' => ['orderId' => $orderId, 'orderNo' => $data['order_no'], 'expireAt' => $data['expire_at']]];
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function hallPayOrder($orderNo, $isBag, $type, $payPassword, $paySubType): array
    {
        if (!RedLock::getInstance()->lock('hallPayOrder:' . $orderNo, 1)) {
            CommonUtil::throwException(ErrorConst::FREQUENT_ERROR, ErrorConst::FREQUENT_ERROR_MSG);
        }

        if (!in_array($type, [1, 2, 3, 4])) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }

        //获取订单
        $where = [
            ['order_no', '=', $orderNo],
        ];
        $orderInfo = CommunityOrder::getInstance()->where($where)->find();
        //订单不存在 订单状态错误      订单用户id错误 ，订单时间超时
        if (empty($orderInfo) || $orderInfo['status'] != 1 || $orderInfo['user_id'] != $this->userinfo->id || $orderInfo['expireAt'] < date('Y-m-d H:i:s')) {
            CommonUtil::throwException(ErrorConst::NO_ORDER_ERROR, ErrorConst::NO_ORDER_ERROR_MSG);
        }

        if ($type == 3) {
            $account = MemberService::getInstance()->account($this->userinfo->id);
            if (empty($account)) {
                CommonUtil::throwException(ErrorConst::NO_PAY_PASSWORD_ERROR, ErrorConst::NO_PAY_PASSWORD_ERROR_MSG);
            }

            //验证支付密码
            if ($account['payPwd'] != $payPassword) {
                CommonUtil::throwException(ErrorConst::PAY_PASSWORD_ERROR, ErrorConst::PAY_PASSWORD_ERROR_MSG);
            }
        }
        $communityUser = CommunityUser::getInstance()->where('community_id',$orderInfo['communityId'])->find();
        if($communityUser['communityStatus'] == CommunityConst::PERMANENT_STATUS){
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, '社区已被抢购');
        }

        $amountPrice = 0;
        $signPrice = 0;
        //获取余额
        if ($type == 3) {
            $userBalance = MemberService::getInstance()->finance($this->userinfo->id);
            $amountPrice = $userBalance['amount'];
        }
        //获取红包
        if ($isBag) {
            $userBag = CommunityService::getInstance()->getUserBag($this->userinfo->id);
            $signPrice = $userBag['communityAmount'] ?? 0;
        }

        $price = $orderInfo['price'];
        $payPrice = bcsub($price, $signPrice, 2);
        $isBalance = 0;
        if ($type == 3 && $amountPrice < $payPrice) {
            CommonUtil::throwException(ErrorConst::NO_PRICE_ERROR, ErrorConst::NO_PRICE_ERROR_MSG);
        }
        if ($type == 3) {
            //社区余额
            $amountPrice = $payPrice;
            $thirdPayPrice = 0;
            $isBalance = 1;
        } else {
            $thirdPayPrice = $payPrice;
        }

        $payInfo = CommunityService::getInstance()->payOrder($orderInfo, $thirdPayPrice, $amountPrice, $signPrice, $type);
        if (!$payInfo) {
            CommonUtil::throwException(ErrorConst::SYSTEM_ERROR, ErrorConst::SYSTEM_ERROR_MSG);
        }
        $userInfo = MemberService::getInstance()->getUserInfo($this->userinfo->id);
        $pay = [];
        if ($isBalance) {
            //余额全付
            $info = [
                'pay_status' => 3,
                'pay_no' => $payInfo['pay_no'],
                'money' => $payInfo['community_pay_amount'],
                'trade_no' => '',
                'receipt_data' => '',
            ];

            //$info = PayService::getInstance()->payFormOrder($info);
            $event["exchange"] = config('rabbitmq.order_callback_queue');
            RabbitMqService::send($event, $info);
            if (!$info) {
                CommonUtil::throwException(ErrorConst::SYSTEM_ERROR, ErrorConst::SYSTEM_ERROR_MSG);
            }
        } elseif ($type == 4) {
            //杉德支付
            $ret = SandLogic::getInstance()->accountBalanceQuery($this->userinfo->id);
            if (empty($ret)) {
                CommonUtil::throwException(ErrorConst::PARAM_ERROR, '个人钱包未开户');
            }
            if (env('test.is_test') == 1) {
                if ($ret['accountList'][0]['availableBal'] < 0.01) {
                    CommonUtil::throwException(ErrorConst::NO_PRICE_ERROR, ErrorConst::NO_PRICE_ERROR_MSG);
                }
            } else {
                if ($ret['accountList'][0]['availableBal'] < $thirdPayPrice) {
                    CommonUtil::throwException(ErrorConst::NO_PRICE_ERROR, ErrorConst::NO_PRICE_ERROR_MSG);
                }
            }
            if (env('test.is_test') == 1) {
                $thirdPayPrice = 0.01;
            }
            $pay = SandLogic::getInstance()->orderCreate($this->userinfo->id, $thirdPayPrice, $payInfo['pay_no']);
        } else {
            $pay = PayService::getInstance()->toPay($payInfo, $userInfo, $type, $paySubType);
        }

        return ['payInfo' => $pay, 'isBalance' => $isBalance];
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function communityHallOrderPreview($communityId, $cateId): array
    {
        if (!RedLock::getInstance()->lock('communityHallOrderPreview:' . $this->userinfo->id . ':' . request()->ip(), 1)) {
            CommonUtil::throwException(ErrorConst::FREQUENT_ERROR, ErrorConst::FREQUENT_ERROR_MSG);
        }
        if (!in_array($cateId, [3, 4])) {
            CommonUtil::throwException(ErrorConst::FREQUENT_ERROR, ErrorConst::FREQUENT_ERROR_MSG);
        }
        $account = MemberAccountCache::getKeyData($this->userinfo->id);
        if (empty($account) || $account['is_active_sd'] != 1) {
            CommonUtil::throwException(ErrorConst::SAND_NO_BIND_ERROR, ErrorConst::SAND_NO_BIND_ERROR_MSG);
        }

        $community = Community::getInstance()->where('id', $communityId)->find();
        if (empty($community)) {
            CommonUtil::throwException(ErrorConst::FREQUENT_ERROR, ErrorConst::FREQUENT_ERROR_MSG);
        }

        //占位中
        $seconds = 15;

        $config = CommunityService::getInstance()->getCommunityConfig('buy_community_config');

        //招募大厅
        if ($cateId == 3) {
            $communityInfo = CommunityUser::getInstance()->where('community_id', $communityId)->find();
            if (empty($communityInfo)) {
                $communityInfo['communityName'] = $community['name'];
            } else {
                if ($communityInfo['userId'] == $this->userinfo->id) {
                    CommonUtil::throwException(ErrorConst::PARAM_ERROR, '不能购买自己的社区');
                }
            }
            $communityInfo['price'] = $config['buy_price'];
        } else {
            //经营中转让
            $communityInfo = CommunityUser::getInstance()->where('community_id', $communityId)->find();
            if (empty($communityInfo)) {
                CommonUtil::throwException(ErrorConst::PARAM_ERROR, '社区不存在');
            }
            if ($communityInfo['userId'] == $this->userinfo->id) {
                CommonUtil::throwException(ErrorConst::PARAM_ERROR, '不能购买自己的社区');
            }
            if ($communityInfo['is_op_transfer'] == 0) {
                CommonUtil::throwException(ErrorConst::PARAM_ERROR, '不是转让社区');
            }
            $communityInfo['price'] = $communityInfo['op_price'];
            $communityInfo['create_at'] = $communityInfo['op_time'];
        }

        $data['rule'] = SysLogic::getInstance()->getArticle('partner');
        $communityInfo['img'] = '';
        $data['community'] = $communityInfo;
        $data['seconds'] = $seconds;
        $data['goods'] = CommunityService::getInstance()->getCommunityGoods();
        return $data;
    }

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function getLastCommunityAccount($communityId)
    {
        $where = [
            ['community_id', '=', $communityId],
        ];
        $userId = CommunityUser::getInstance()->where('community_id', $communityId)->value('user_id');
        if ($userId == 0) {
            return ['real_name' => '日兮香文化科技(海南)有限公司'];
        }
        $order = CommunityOpOrder::getInstance()->where($where)->field('user_id,order_no,image,sign_image')->order('id desc')->find();
        if (empty($order)) {
            return [];
        }

        $info = MemberAccountCache::getKeyData($order['userId']);
        //$info['real_name'] = !empty($info['real_name']) ? mb_substr($info['real_name'], 0, 1) . '**' : '';
        //$info['idc'] = !empty($info['idc']) ? substr_replace($info['idc'], ' **** **** **** ', 2, 12) : '';
        $info['orderNo'] = !empty($order['orderNo']) ? $order['orderNo'] : '';
        $info['image'] = !empty($order['image']) ? $order['image'] : '';
        $info['signImage'] = !empty($order['signImage']) ? $order['signImage'] : '';
        return $info;
    }

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function getCommunityOrderList($startAt, $endAt, $page, $pageSize, $logType): array
    {
        $where = [
            ['user_id', '=', $this->userinfo->id],
        ];

        if ($logType) {
            switch ($logType) {
                case 'common':
                    $where[] = [
                        'type', '<>', 4
                    ];
                    break;
                case 'prepay':
                    $where[] = [
                        'type', '=', 4
                    ];
                    break;
            }
        }

        if (!empty($startAt) && !empty($endAt)) {
            $endAt = $endAt . ' 23:59:59';
            $where[] = ['create_at', 'between', [$startAt, $endAt]];
        }

        $list = CommunityOrder::getInstance()
            ->where($where)
            ->order('id desc')
            ->page($page, $pageSize)
            ->select();

        $list = empty($list) ? [] : $list->toArray();

        foreach ($list as &$val) {
            $val['days'] = date('m-d', strtotime($val['createAt']));
        }
        $arr = [];
        $payArr = [1 => '微信',2 => '支付宝',3 => '余额', 4 => '电子钱包'];
        foreach ($list as &$v) {
            $communityUser = CommunityUser::getInstance()->where('community_id', $v['communityId'])->find();
            $v['address'] = $communityUser['address'] ?? '';
            $v['communityName'] = $communityUser['communityName'] ?? '';
            $orderPay = OrderPay::getInstance()->where('order_no',$v['orderNo'])->order('id desc')->find();
            $v['payTypeName'] = isset($orderPay['payStatus']) ? $payArr[$orderPay['payStatus']] : '';
            $v['isRefund'] = $orderPay['isRefund'] ?? 0;
            $v['refundTime'] = $orderPay['refundTime'] ?? 0;
            $arr[$v['days']][] = $v;
        }
        return [
            'typeArr' => $this->logTypeData(),
            'rows' => $arr,
        ];
    }

    public function logTypeData(): array
    {
        return [
            ['key' => '', 'name' => '全部'],
            ['key' => 'common', 'name' => '普通订单'],
            ['key' => 'prepay', 'name' => '预约订单'],
        ];
    }

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function inPrepayPayOrder(): array
    {
        $where = [
            ['user_id', '=', $this->userinfo->id],
            ['status', '=', 1],
            ['deleted', '=', 0],
            ['create_at', '>=', date('Y-m-d')]
        ];
        $field = 'status,order_no,id,community_id,pay_price,create_at';
        $list = PrepayCommunityOrder::getInstance()->where($where)->field($field)->order('id desc')->find();
        if (empty($list)) {
            return [];
        }
        $list = $list->toArray();

        $list['exTime'] = (strtotime($list['createAt']) + 60) - time();
        $list['exTime'] = max($list['exTime'], 0);

        return $list;
    }

    public function rankRule(): array
    {
        $where = [
            ['is_switch','=',1],
            ['status','=',1],
            ['deleted','=',0]
        ];
        $rule = Rank::getInstance()->where($where)->order('id desc')->value('remark') ?: '';
        return ['rule' => $rule];
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function changeDeduction($communityId): array
    {
        CommonUtil::throwException(ErrorConst::PARAM_ERROR, '暂不能兑换');
        if (!RedLock::getInstance()->lock('changeDeduction:' . $this->userinfo->id, 1)) {
            CommonUtil::throwException(ErrorConst::FREQUENT_ERROR, ErrorConst::FREQUENT_ERROR_MSG);
        }

        if(empty($communityId)){
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, 'communityId不能为空');
        }
        $where= [
            ['user_id','=',$this->userinfo->id],
            ['community_id','=',$communityId],
        ];
        $communityUser = CommunityUser::getInstance()->where($where)->find();
        if(empty($communityUser)){
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, '社区不存在');
        }
        if($communityUser['community_status'] != 6){
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, '社区状态错误');
        }
        $order = CommunityOrder::getInstance()->where('id',$communityUser['lastOrderId'])->find();
        if(empty($order)){
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, '订单不存在');
        }

        $price = $order['totalAmount'];
        //裂变订单 本金、溢价收益拆分
        if ($order['isFission']) {
            $price = bcmul($order['totalAmount'], 0.5, 2);
        }
        Finance::getInstance()->startTrans();
        try{
            $msg = '社区兑换';
            $ret = MemberService::getInstance()->addFinanceLog($this->userinfo->id, 'community_change', 0, 8, $msg, '', 1, 0,$price);
            if(!$ret){
                Finance::getInstance()->rollback();
                CommonUtil::throwException(ErrorConst::PARAM_ERROR, '更新抵扣券失败');
            }
            $data = [
                'user_id' => 0,
                'community_status' => 0,
                'last_order_id' => 0,
                'type' => 0, //社区广场
                'is_pay_service' => 0,
                'is_sign' => 0,
                'lock_status' => 1,
                'last_enter_amount' => 0,
                'total_amount' => 0,
                'user_amount' => 0,
                'user_count' => 0,
                'shop_num' => 0,
                'shop_amount' => 0,
                'op_order_no' => '',
                'last_op_order_no' => '',
                'op_price' => 0,
                'activity_id' => 0,
                'is_first' => 0,
                'user_ids' => '',
            ];
            $ret = CommunityUser::getInstance()->where('community_id',$communityId)->update($data);
            if(!$ret){
                Finance::getInstance()->rollback();
                CommonUtil::throwException(ErrorConst::PARAM_ERROR, '更新社区失败');
            }
            $data = [
                'user_id' => $this->userinfo->id,
                'order_no' => $order['orderNo'],
                'community_name' => $communityUser['communityName'],
                'community_id' => $communityId,
                'price' => $price,
                'snapshot' => json_encode($communityUser->toArray(),256),
            ];
            $ret = CommunityChangeLog::getInstance()->insert($data);
            if(!$ret){
                Finance::getInstance()->rollback();
                CommonUtil::throwException(ErrorConst::PARAM_ERROR, '更新兑换记录失败');
            }
        }catch (\Exception $e){
            Finance::getInstance()->rollback();
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, $e->getMessage());
        }
        Finance::getInstance()->commit();
        return ['money' => $order['totalAmount']];
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function limitCount($communityId = 0): bool
    {
        $buyStatus = Member::getInstance()->where('id',$this->userinfo->id)->value('buy_status');
        $transferConfig = CommunityService::getInstance()->getCommunityConfig('transfer_config');
        if($buyStatus == 0 && isset($transferConfig['status']) && $transferConfig['status'] == 1){
            $where = [
                ['user_id','=',$this->userinfo->id],
                ['create_at','>=',date('Y-m-d')],
            ];
            $count = CommunityOpOrder::getInstance()->where($where)->count();
            $everyCount = CommunityService::getInstance()->everyTransferCount($this->userinfo->id);
            if($count >= $everyCount){
                CommonUtil::throwException(ErrorConst::PARAM_ERROR, '暂无转让次数');
            }
        }

        $memberNum = MemberInfoService::getInstance()->memberNum($this->userinfo->id);
        if($buyStatus == 0 && isset($transferConfig['limit_status']) && $transferConfig['limit_status'] == 1){
            $now = date('Y-m-d H:i:s');
            if($now >= $transferConfig['start_time'] && $now <= $transferConfig['end_time']){
                $where = [
                    ['user_id','=',$this->userinfo->id],
                    ['status','=',1]
                ];
                $lock = CommunityLockLog::getInstance()->where('user_id',$this->userinfo->id)->order('id desc')->find();
                if(!empty($lock)){
                    $where[] = ['create_at','>=',$lock['createAt']];
                }
                $userTotal = MemberCommunityAmountLog::getInstance()->where($where)->sum('amount') ?: 0;
                $max = CommunityService::getInstance()->transferMaxMoney($this->userinfo->id);
                if($userTotal >= $max){
                    CommonUtil::throwException(ErrorConst::PARAM_ERROR, '您的收益达到上限，需锁定一个考核中社区');
                }
                if(empty($memberNum) || $memberNum['transferCount'] < 1){
                    CommonUtil::throwException(ErrorConst::PARAM_ERROR, '您还没有入驻社区');
                }
            }
        }

        $transferGt = CommunityService::getInstance()->getCommunityConfig('transfer_gt');
        if($buyStatus == 0 && $transferGt > 0){
            $where = [
                ['community_id','=',$communityId],
                ['community_status','=',6],
                ['user_id','=',$this->userinfo->id]
            ];
            $communityUser = CommunityUser::getInstance()->where($where)->find();
            //入驻金额<1500，转让社区本金<1500
            //入驻金额>=1500，转让社区本金>=1500
            if($communityUser['lastEnterAmount'] > $transferGt){
                //今天抢的社区
                $where = [
                    ['user_id','=',$this->userinfo->id],
                    ['last_enter_time','>=',date('Y-m-d')],
                ];
                $money = CommunityUser::getInstance()->where($where)->order('last_enter_amount desc')->value('last_enter_amount');
                if($money <= $transferGt){
                    CommonUtil::throwException(ErrorConst::PARAM_ERROR, '入驻金额不足');
                }
            }
        }

        return true;
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function communityUserTransfer($communityId, $phone, $realName,$password): bool
    {
        if (!RedLock::getInstance()->lock('communityUserTransfer:' . $this->userinfo->id, 1)) {
            CommonUtil::throwException(ErrorConst::FREQUENT_ERROR, ErrorConst::FREQUENT_ERROR_MSG);
        }
        if(empty($communityId)){
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, '社区communityId不能为空');
        }
        if(empty($phone)){
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, '请输入账号');
        }
        if(empty($realName)){
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, '对方实名不能为空');
        }
        if(empty($password)){
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, '支付密码不能为空');
        }
        $payPwd = Account::getInstance()->where('user_id',$this->userinfo->id)->value('pay_pwd');
        if(empty($payPwd) || $password != $payPwd){
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, '支付密码错误');
        }
        $where = [
            ['phone','=',$phone],
            ['deleted','=',0],
            ['is_logout','=',0],
        ];
        $member = Member::getInstance()->where($where)->find();
        if(empty($member)){
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, '账号不存在');
        }
        $account = Account::getInstance()->where('user_id',$member['id'])->find();
        if(empty($account) || empty($account['realName'])){
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, '对方未实名认证');
        }
        if($account['real_name'] != $realName){
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, '对方真实姓名填写错误');
        }
        if($account['is_active_sd'] != 1){
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, '对方未激活电子钱包');
        }
        $where = [
            ['user_id','=',$this->userinfo->id],
            ['community_id','=',$communityId]
        ];
        $communityUser = CommunityUser::getInstance()->where($where)->find();
        if(empty($communityUser)){
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, '社区不存在');
        }
        $order = CommunityOrder::getInstance()->where('id',$communityUser['lastOrderId'])->find();
        if(empty($order)){
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, '社区不存在');
        }
        CommunityUserTransferLog::getInstance()->startTrans();
        try{
            $communityUser->user_id = $member['id'];
            $ret = $communityUser->save();
            if(!$ret){
                CommunityUserTransferLog::getInstance()->rollback();
                CommonUtil::throwException(ErrorConst::PARAM_ERROR, '更新社区失败');
            }
            $data = [
                'user_id' => $this->userinfo->id,
                'to_user_id' => $member['id'],
                'community_id' => $communityId,
                'order_id' => $communityUser['lastOrderId'],
                'to_user_name' => $member['userName'],
                'to_real_name' => $realName,
                'community_name' => $communityUser['communityName'],
                'snapshot' => !empty($order) ? json_encode($order->toArray(),256) : "",
            ];
            $ret = CommunityUserTransferLog::getInstance()->insert($data);
            if(!$ret){
                CommunityUserTransferLog::getInstance()->rollback();
                CommonUtil::throwException(ErrorConst::PARAM_ERROR, '更新社区转让失败');
            }
            $ret = CommunityOrder::getInstance()->where('id',$communityUser['lastOrderId'])->update(['user_id' => $member['id']]);
            if(!$ret){
                CommunityUserTransferLog::getInstance()->rollback();
                CommonUtil::throwException(ErrorConst::PARAM_ERROR, '更新社区转让失败');
            }
        }catch (\Exception $e){
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, $e->getMessage());
        }
        CommunityUserTransferLog::getInstance()->commit();
        return true;
    }

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function communityUserTransferLog($page, $pageSize): array
    {
        $list = CommunityUserTransferLog::getInstance()
            ->where('user_id',$this->userinfo->id)
            ->page($page,$pageSize)
            ->order('id desc')
            ->select();
        foreach($list as &$v){
            $phone = Member::getInstance()->where('id',$v['toUserId'])->value('phone');
            $v['phone']    = substr_replace(($phone ?? ''), "****", 3, 4);
            $v['toRealName'] = CommonUtil::substrRealName($v['toRealName']);
        }
        return ['rows' => !empty($list) ? $list->toArray() : []];
    }

}
